如何使用 JAVA 8 从地图中获取第一个键值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43627091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:36:21  来源:igfitidea点击:

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

javajava-8iteratorjava-stream

提问by 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 ?

有没有更干净的方法可以用 java8 做到这一点?

回答by 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().
  • 如果地图为空,它将抛出异常
  • HashMap例如,a没有顺序 - 所以你的方法实际上getAny()比 a更像是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.

它返回一个Optional.

回答by Eugene

Seems like you need findFirsthere

好像你需要findFirst这里

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

Obviously a HashMaphas no order, so findFirst might return a different result on different calls. Probably a more suitable method would be findAnyfor your case.

显然 aHashMap没有顺序,因此 findFirst 可能会在不同的调用中返回不同的结果。可能更适合findAny您的情况的方法。