zoukankan      html  css  js  c++  java
  • 怎么在java 8的map中使用stream

    怎么在java 8的map中使用stream

    简介

    Map是java中非常常用的一个集合类型,我们通常也需要去遍历Map去获取某些值,java 8引入了Stream的概念,那么我们怎么在Map中使用Stream呢?

    基本概念

    Map有key,value还有表示key,value整体的Entry。

    创建一个Map:

    Map<String, String> someMap = new HashMap<>();
    

    获取Map的entrySet:

    Set<Map.Entry<String, String>> entries = someMap.entrySet();
    

    获取map的key:

    Set<String> keySet = someMap.keySet();
    

    获取map的value:

    Collection<String> values = someMap.values();
    

    上面我们可以看到有这样几个集合:Map,Set,Collection。

    除了Map没有stream,其他两个都有stream方法:

    Stream<Map.Entry<String, String>> entriesStream = entries.stream();
            Stream<String> valuesStream = values.stream();
            Stream<String> keysStream = keySet.stream();
    

    我们可以通过其他几个stream来遍历map。

    使用Stream获取map的key

    我们先给map添加几个值:

    someMap.put("jack","20");
    someMap.put("bill","35");
    

    上面我们添加了name和age字段。

    如果我们想查找age=20的key,则可以这样做:

    Optional<String> optionalName = someMap.entrySet().stream()
                    .filter(e -> "20".equals(e.getValue()))
                    .map(Map.Entry::getKey)
                    .findFirst();
    
            log.info(optionalName.get());
    

    因为返回的是Optional,如果值不存在的情况下,我们也可以处理:

    optionalName = someMap.entrySet().stream()
                    .filter(e -> "Non ages".equals(e.getValue()))
                    .map(Map.Entry::getKey).findFirst();
    
            log.info("{}",optionalName.isPresent());
    

    上面的例子我们通过调用isPresent来判断age是否存在。

    如果有多个值,我们可以这样写:

    someMap.put("alice","20");
            List<String> listnames = someMap.entrySet().stream()
                    .filter(e -> e.getValue().equals("20"))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
    
            log.info("{}",listnames);
    

    上面我们调用了collect(Collectors.toList())将值转成了List。

    使用stream获取map的value

    上面我们获取的map的key,同样的我们也可以获取map的value:

    List<String> listAges = someMap.entrySet().stream()
                    .filter(e -> e.getKey().equals("alice"))
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
    
            log.info("{}",listAges);
    

    上面我们匹配了key值是alice的value。

    总结

    Stream是一个非常强大的功能,通过和map相结合,我们可以更加简单的操作map对象。

    本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/stream-formap

    欢迎关注我的公众号:程序那些事,更多精彩等着您!
    更多内容请访问 www.flydean.com

  • 相关阅读:
    placement new小结
    template template parameter 模板模板参数
    windows下创建和删除软链接
    gcc下载地址
    map的erase函数小结
    typedef函数指针
    宏定义条件编译中使用多条件
    关于c++模板特例化测试
    tolua使用
    c++多态
  • 原文地址:https://www.cnblogs.com/flydean/p/java-8-map-stream.html
Copyright © 2011-2022 走看看