Check value in map java

Check if ‘Key’ exists in a hashmap [duplicate]

I have a hashmap with Key and Value being ‘String’. I want to check if a particular key exists by ignoring string after ‘$’ in the Key. Hashmap contains keys as ‘acctId$accountId’, ‘acctId$desc’, ‘acctId$crncyCode’ etc.

Iterator itx = uiToSrvFldMapList.entrySet().iterator(); if(uiToSrvFldMapList.containsKey(cellId))< String sSrvFld = (String) uiToSrvFldMapList.get("acctId"); System.out.println("sSrvFld :: " +sSrvFld); 

Why dont you just use a stacked map? Something like Map> would make access easier and faster. You could then check for myMap.get(firstPart).get(secondPart) . Of course you have to ceck if the first one is not null . This would also be better for your running time.

4 Answers 4

public static void main(String[] args) < String s = "acctId$accountId"; s = s.replaceAll("\\$.*", "");// remove everything after $ System.out.println(s); // do hm.get(s) here >

I hope this might help you

 Map map = new HashMap(); map.put("abc$def","ABC"); map.put("ab","A"); map.put("de","b"); String key = "abc$def"; String s[] = key.split("$"); if(map.containsKey(s[0])) System.out.println("Value is: "+map.get(key)); else System.out.println("cannot find.."); 

Supposing that in "acctId$accountId" you will have the same String both as "acctId" and "accountId", you can search for it in the following way:

 `Map uiToSrvFldMapList = new HashMap(); uiToSrvFldMapList.put("0000$0000", "test"); // just an example uiToSrvFldMapList.put("0000$0001", "description"); // just an example uiToSrvFldMapList.put("0001$0000", "2test"); // just an example uiToSrvFldMapList.put("0001$0001", "2description"); // just an example String acctId = "0000"; // the account id string if(uiToSrvFldMapList.containsKey(acctId +"$" + acctId))< String sSrvFld = (String) uiToSrvFldMapList.get(acctId + "$" + acctId); System.out.println("sSrvFld :: " +sSrvFld); >` 

This is a test program, which shows a way to achieve this functionality:

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Test < public static void main(String[] args) < MapuiToSrvFldMapList = new HashMap(); uiToSrvFldMapList.put("acctId$accountId", "accid"); uiToSrvFldMapList.put("acctId$desc", "accdesc"); uiToSrvFldMapList.put("acctId$crncyCode", "currencyCode"); uiToSrvFldMapList.put("smthElse$smthElse", "smthElse"); List valuesContainingKey = valuesContainingKeys( uiToSrvFldMapList, "acctId"); // Returns if the key is contained if (valuesContainingKey.isEmpty()) < System.out.println("The key is not contained in the map"); >else < System.out.println("The part of the key is in the map"); >System.out .println("All values, where the corresponding key contains the subkey: "); for (String s : valuesContainingKey) < System.out.println(s); >> /** * * @param map * Map containing the key-value pairs * @param searchString * A String used as a subkey, for which is searched if it is * contained as a substring at the beginning of a key in the map * @return List of all Values from the map, whose corresponding key contains * searchString */ private static List valuesContainingKeys(Map map, String searchString) < ListcontainingKeys = new ArrayList(); for (Entry e : map.entrySet()) < if (e.getKey().startsWith(searchString)) < containingKeys.add(e.getValue()); >> return containingKeys; > > 

Simply write the method valuesContainingKeys (not needed to be static) where you want this functionality. This method will return a list of all values, whose corresponding key contains the string you are looking for. Simply checking valuesContainingKey.isEmpty() will return if there is no value, for which the corresponding key begins with the searched key.

Читайте также:  Integer division and modulo python

Источник

How to verify if a value in HashMap exist

I have the following HashMap where the key is a String and the value is represented by an ArrayList :

 HashMap> productsMap = AsyncUpload.getFoodMap(); 

I also have another ArrayList foods implemented in my application. My question is, What would be the best way to find out if my HashMap contains a Specific String from my second ArrayList ? I have tried without success:

Iterator keySetIterator = productsMap.keySet().iterator(); Iterator valueSetIterator = productsMap.values().iterator(); while(keySetIterator.hasNext() && valueSetIterator.hasNext()) < String key = keySetIterator.next(); if(mArrayList.contains(key))< System.out.println("Yes! its a " + key); >> 

alternative way without loops productsMap.toString().contains(key) . Of course there can be some problems like, key can be part of some different value or map key and this is not for big maps. Anyway it's just an option.

7 Answers 7

// fast-enumerating map's values for (ArrayList value: productsMap.values()) < // using ArrayList#contains System.out.println(value.contains("myString")); >

And if you have to iterate over the whole ArrayList , instead of looking for one specific value only:

// fast-enumerating food's values ("food" is an ArrayList) for (String item: foods) < // fast-enumerating map's values for (ArrayListvalue: productsMap.values()) < // using ArrayList#contains System.out.println(value.contains(item)); >> 

Past time I updated this with some Java 8 idioms.

The Java 8 streams API allows a more declarative (and arguably elegant) way of handling these types of iteration.

For instance, here's a (slightly too verbose) way to achieve the same:

// iterate foods foods .stream() // matches any occurrence of. .anyMatch( // . any list matching any occurrence of. (s) -> productsMap.values().stream().anyMatch( // . the list containing the iterated item from foods (l) -> l.contains(s) ) ) 

. and here's a simpler way to achieve the same, initially iterating the productsMap values instead of the contents of foods :

// iterate productsMap values productsMap .values() .stream() // flattening to all list elements .flatMap(List::stream) // matching any occurrence of. .anyMatch( // . an element contained in foods (s) -> foods.contains(s) ) 

I have some additional doubt in the if "myString" values not known completely ,I know only just myStri .How to verify that or find the complete value by using contains some charactes as "myStri". Could you help me please.@Mena.or anyone

You need to use the containsKey() method. To do this, you simply get the hashMap you want the key out of, then use the containsKey method, which will return a boolean value if it does. This will search the whole hashMap without having to iterate over each item. If you do have the key, then you can simply retrieve the value.

It might look something like:

if(productsMap.values().containsKey("myKey")) < // do something if hashMap has key >

public boolean containsKey (Object key) Added in API level 1

Returns whether this map contains the specified key. Parameters key the key to search for. Returns

true if this map contains the specified key, false otherwise. 

why does it named containsKey rather than containsValue though? If the purpose is to know whether it contain value or not.

public boolean anyKeyInMap(Map> productsMap, List keys) < SetkeySet = new HashSet<>(keys); for (ArrayList strings : productsMap.values()) < for (String string : strings) < if (keySet.contains(string)) < return true; >> > return false; > 
hashMap.containsValue("your value"); 

Will check if the HashMap contains the value

Iterator keySetIterator = productsMap.keySet().iterator(); Iterator valueSetIterator = productsMap.values().iterator(); while(keySetIterator.hasNext()) < String key = keySetIterator.next(); if(valueSetIterator.next().contains(key))< // corrected here System.out.println("Yes! its a " + key); >> 

If you want the Java 8 way of doing it, you could do something like this:

 private static boolean containsValue(final Map> map, final String value) < return map.values().stream().filter(list ->list.contains(value)).findFirst().orElse(null) != null; > 
 private static boolean containsValue(final Map> map, final String value) < return map.values().stream().filter(list ->list.contains(value)).findFirst().isPresent(); > 

Both should produce pretty much the same result.

Here's a sample method that tests for both scenarios. Searching for items in map's keys and also search for items in the lists of each map entry:

private static void testMapSearch() < final ArrayListfruitsList = new ArrayList(); fruitsList.addAll(Arrays.asList("Apple", "Banana", "Grapes")); final ArrayList veggiesList = new ArrayList(); veggiesList.addAll(Arrays.asList("Potato", "Squash", "Beans")); final Map productsMap = new HashMap(); productsMap.put("fruits", fruitsList); productsMap.put("veggies", veggiesList); final ArrayList foodList = new ArrayList(); foodList.addAll(Arrays.asList("Apple", "Squash", "fruits")); // Check if items from foodList exist in the keyset of productsMap for(String item : foodList) < if(productsMap.containsKey(item))< System.out.println("productsMap contains a key named " + item); >else < System.out.println("productsMap doesn't contain a key named " + item); >> // Check if items from foodList exits in productsMap's values for (Map.Entry entry : productsMap.entrySet()) < System.out.println("\nSearching on list values for key " + entry.getKey() + ".."); for(String item : foodList)< if(entry.getValue().contains(item))< System.out.println("productMap's list under key " + entry.getKey() + " contains item " + item); >else < System.out.println("productMap's list under key " + entry.getKey() + " doesn't contain item " + item); >> > > 

productsMap doesn't contain a key named Apple

productsMap doesn't contain a key named Squash

productsMap contains a key named fruits

Searching on list values for key fruits..

productMap's list under key fruits contains item Apple

productMap's list under key fruits doesn't contain item Squash

productMap's list under key fruits doesn't contain item fruits

Searching on list values for key veggies..

productMap's list under key veggies doesn't contain item Apple

productMap's list under key veggies contains item Squash

productMap's list under key veggies doesn't contain item fruits

Источник

Key existence checking utility in Map

My goal is: if key does not exist in map, the map implementation throws an exception with the passed string. I don't know whether or not my desire is reasonable? (Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)

Little hint to your code: return true; in your else block instead of return map_instance.containsKey(key); , another invocation of that method is redundant (if this code is used only by one thread at a time)

@MarkoTopolnik You are probably right, but just in case I will leave that comment so OP can notice that there is something to improve there.

6 Answers 6

I use Optional Java util class, e.g.

Optional.ofNullable(elementMap.get("not valid key")) .orElseThrow(() -> new ElementNotFoundException("Element not found")); 

Good proposal, but it doesn't work when the map has an entry with null as a key on the map.as it would throw the exception rather than returning the associated value.

This totally works, however, it's an abuse of the Optional data type per its author: stackoverflow.com/a/26328555 Optional is to be used as a return type, not as a way to branch through chaining in operational code.

There is one more nice way to achieve this:

return Objects.requireNonNull(map_instance.get(key), "Specified key doesn't exist in map"); 
  • only NullPointerException - sometimes NoSuchElementException or custom exceptions are more desirable

In Java 8 you can use computeIfAbsent from Map , like this:

map.computeIfAbsent("invalid", key -> < throw new RuntimeException(key + " not found"); >); 

Don’t do this. "computeIfAbsent" is meant as a mutation operation. So if your map happens to be an UnmodifiableMap, or a Guava or Eclipse Collection ImmutableMap, or a ProtoMap, this call will immediately fail with some sort of UnsupportedOperationException. A Java8 equivalent could be: Optional.fromNullable(map.get("invalid")).orElseThrow(() -> new RuntimeException(key + " not found")); This has slightly more bloat, but has the advantage of correctness.

Great comment. But the proposed alternative doesn't work when there is an entry with null as a key on the map, as it would throw the exception rather than returning the associated value.

You could take a look into the configuration map from Apache commons. It doesn't implements Map , but has a similar interface with a few Helper methods, like getString , getStringArray , getShort and so on.

With this implementation you could use the method setThrowExceptionOnMissing(boolean throwExceptionOnMissing) and could catch it and handle as you want.

Isn't exactly with a configurable message but from my point of view it doesn't make sense to throw a fixed exception just with a custom message since the exception type itself depends on the context where the get method is invoked. For example, if you perform a get of an user the exception would be something related to that, maybe UserNotFoundException , and not just a RuntimeException with the message: User not Found in Map!

Источник

Оцените статью