欢迎光临
我们一直在努力

Java 8中如何获取Map对象的第一个元素

在Java 8中可以通过下面的方式获取Map对象的第一个元素:

1.获取元素键

//if order is important, e.g. with a TreeMap/LinkedHashMap
map.keySet().stream().findFirst();

//if order is not important or with unordered maps (HashMap...)
map.keySet().stream().findAny();

2.获取元素键值

//if order is important, e.g. with a TreeMap/LinkedHashMap
map.values().stream().findFirst();

//if order is not important or with unordered maps (HashMap...)
map.values().stream().findAny();

3.获取元素

//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();

References

  1. How to get the first key value from map using JAVA 8?
  2. Java中Map对象的values()/keySet()/entrySet()区别
赞(2) 打赏
未经允许不得转载:Ddmit » Java 8中如何获取Map对象的第一个元素

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册