Lambda in Stream.map/filter not called

后端 未结 4 932
执笔经年
执笔经年 2021-01-18 04:56

I\'m trying to find separate the duplicates and non-duplicates in a List by adding them to a Set and List while using Stream.fil

4条回答
  •  星月不相逢
    2021-01-18 05:37

    In order to the filter to be applied, you need to call a terminal operation like collect(). In that case you can assign the items which pass the filter directly to the extras list instead of use map function.

    Try something like this:

    List strings = Arrays.asList("foo", "bar", "foo", "baz", "foo", "bar");
    
    Set distinct = new HashSet<>();
    
    List extras = strings
                         .stream()
                         .filter(x -> !distinct.add(x))
                         .collect(Collectors.toList());
    

提交回复
热议问题