【问题标题】:Is there any way to return the element that does not pass a filter in stream? [duplicate]有什么方法可以返回未在流中通过过滤器的元素? [复制]
【发布时间】:2021-11-08 23:16:50
【问题描述】:

我有一个字符串元素列表,我想应用过滤器将列表分成两个子列表,以“el”开头的元素和其他元素。 有没有办法只使用一个过滤器来划分列表?

List elements = List.of("e1", "el2", "el3", "4 el", "5 el")

示例:

elements.stream()
        .filter(s -> s.startWith("el))
        .collect( /* something that hold both the element that pass the filter and element that does not */ )

【问题讨论】:

    标签: java filter stream


    【解决方案1】:

    由于您有一个阈值条件来确定一个项目是否将进入组A,否则B,我建议为此使用partitioningBy

    例如:

        List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
        //create the partition map
        Map<Boolean,List<String>> partitionMap = elements.stream()
                .collect(Collectors.partitioningBy(s-> s.startsWith("el")));
    
        //getting the partitions
        List<String> startsWithEl = partitionMap.get(true);
        List<String> notStartingWilEl = partitionMap.get(false);
    

    现在每个列表都将保存它的分区。

    【讨论】:

      【解决方案2】:

      你可以这样做。

      • 使用groupingBy 并创建一个Map&lt;String, List&lt;String&gt;&gt;
      • 如果字符串以“el”组开头,使用els
      • 否则,请使用others
      List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
      Map<String, List<String>> map = elements.stream().collect(
              Collectors.groupingBy(str -> str.startsWith("el") ?
                      "els" : "others"));
      
      map.entrySet().forEach(System.out::println);
      

      打印

      els=[el2, el3]
      others=[e1, 4 el, 5 el]
      

      【讨论】:

        猜你喜欢
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        • 2018-09-17
        • 2020-10-13
        • 2017-10-21
        • 2017-11-02
        相关资源
        最近更新 更多