简体   繁体   English

如何使用JAVA 8从map获取第一个键值?

[英]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 ? 有没有更简洁的方法来使用java8?

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() . 例如, HashMap没有顺序 - 所以你的方法实际上更像是getAny()不是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 . 返回一个Optional

Seems like you need findFirst here 好像你在这里需要findFirst

   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. 显然HashMap没有顺序,因此findFirst可能会在不同的调用上返回不同的结果。 Probably a more suitable method would be findAny for your case. 可能是一个更合适的方法是findAny对你的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM