【问题标题】:Java 8 stream read value from Map in ListJava 8 流从 List 中的 Map 读取值
【发布时间】:2018-05-14 10:02:07
【问题描述】:

我不想使用 foreach 和循环。我想在 Java 8 中使用流在 List 中的 Map 中查找值

List<Map<String, Boolean>> types = ...

map.stream().filter(...

问题是在过滤器中我无法按键/值对搜索。

我想获取所有带有 boolean = true 的元素

我做错了什么?

【问题讨论】:

  • which key 映射到true的所有映射的元素?
  • 是布尔类型 = true 的所有元素
  • 是的,你做错了。你有一个名为types 的变量,然后你调用map.stream(),我们不知道map 来自哪里或它是什么(我们知道它不是Map,因为没有Map.stream())。

标签: java java-stream


【解决方案1】:

流过条目集:

types.stream()                               // stream of maps
    .flatMap(map -> map.entrySet().stream()) // flat map to stream of map entries
    .filter(Map.Entry::getValue)             // filter for value == true
    .map(Map.Entry::getKey)                  // get the key
    .collect(Collectors.toList());           // collect

如果您希望得到一个键/值对列表,您可以删除 .map(Map.Entry::getKey)

【讨论】:

    【解决方案2】:
        List<Map<String, Boolean>> types = new ArrayList<>();
    
        Map<String, Boolean> myMap = new HashMap<>();
        Map<String, Boolean> myMap2 = new HashMap<>();
    
        myMap2.put("Meric", true);
        myMap2.put("BERBER", false);
        types.add(myMap2);
    
        myMap.put("TEST1", true);
        myMap.put("TEST2", false);
        types.add(myMap);
    
    
        types.stream()
                .flatMap(map -> map.entrySet().stream())
                .filter(Map.Entry::getValue)
                .map(Map.Entry::getKey)
                .forEach(System.out::println);
    

    输出将是

     Meric
     TEST1
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2017-01-28
      • 2014-02-09
      • 1970-01-01
      • 2021-09-03
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      相关资源
      最近更新 更多