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

At the moment 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 a cleaner way to do this with java8?

+5
source share
2 answers

I see two problems with your method:

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

With a stream, you can use either:

 //if order is important, eg with a TreeMap/LinkedHashMap map.entrySet().stream().findFirst(); //if order is not important or with unordered maps (HashMap...) map.entrySet().stream().findAny(); 

which returns Optional .

+8
source

Sounds like you need findFirst here

  Optional<Map.Entry<Item, Boolean>> firstEntry = processedItem.entrySet().stream().findFirst(); 

Obviously, the HashMap is out of order, so findFirst may return a different result for different calls. Probably a more suitable method would be findAny for your case.

+6
source

Source: https://habr.com/ru/post/1267171/


All Articles