Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first key value from map using JAVA 8?

As for now I am doing :

Map<Item, Boolean> processedItem = processedItemMap.get(i);

        Map.Entry<Item, Boolean> entrySet = getNextPosition(processedItem);

        Item key = entrySet.getKey();
        Boolean value = entrySet.getValue();


 public static Map.Entry<Item, Boolean> getNextPosition(Map<Item, Boolean> processedItem) {
        return processedItem.entrySet().iterator().next();
    }

Is there any cleaner way to do this with java8 ?

like image 876
user3407267 Avatar asked Apr 26 '17 06:04

user3407267


People also ask

How do I get the value of a Map for a specific key?

HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can we get key from value in Map Java?

Get keys from value in HashMap To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue().

How do I find a key in a HashMap?

util. HashMap. containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.


1 Answers

I see two problems with your method:

  • it will throw an exception if the map is empty
  • a HashMap, for example, has no order - so your method is really more of a getAny() than a getNext().

With a stream you could use either:

//if order is important, e.g. with a TreeMap/LinkedHashMap
map.entrySet().stream().findFirst();

//if order is not important or with unordered maps (HashMap...)
map.entrySet().stream().findAny();

which returns an Optional.

like image 124
assylias Avatar answered Oct 11 '22 22:10

assylias