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

user3407267 :

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 ?

assylias :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464607&siteId=1
Recommended