Lambda in Stream.map/filter not called

后端 未结 4 933
执笔经年
执笔经年 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

    Your code does not work, because the stream is not consumed. You have provided only the intermediate operations, but until you call a terminating operation like forEach, reduce or collect, nothing you have defined in your stream will be invoked.

    You should rather use peek to print the elements going through the stream and collect to get all the elements in the list:

    List extras = strings
        .stream()
        .filter(x -> !distinct.add(x))
        .peek(System.out::println)
        .collect(Collectors.toList());
    

    Using forEach to fill the empty collection created before is a code smell and has nothing to do with functional programming.

提交回复
热议问题