user3407267
user3407267

Reputation: 1634

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 ?

Upvotes: 9

Views: 30943

Answers (2)

Eugene
Eugene

Reputation: 120858

Seems like you need findFirst here

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

Obviously a HashMap has no order, so findFirst might return a different result on different calls. Probably a more suitable method would be findAny for your case.

Upvotes: 8

assylias
assylias

Reputation: 328619

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.

Upvotes: 21

Related Questions