Can Java 8 Streams operate on an item in a collection, and then remove it?

前端 未结 8 1320
不知归路
不知归路 2020-12-23 14:22

Like just about everyone, I\'m still learning the intricacies (and loving them) of the new Java 8 Streams API. I have a question concerning usage of streams. I\'ll provide a

8条回答
  •  情话喂你
    2020-12-23 15:00

    What you really want to do is to partition your set. Unfortunately in Java 8 partitioning is only possible via the terminal "collect" method. You end up with something like this:

    // test data set
    Set set = ImmutableSet.of(1, 2, 3, 4, 5);
    // predicate separating even and odd numbers
    Predicate evenNumber = n -> n % 2 == 0;
    
    // initial set partitioned by the predicate
    Map> partitioned = set.stream().collect(Collectors.partitioningBy(evenNumber));
    
    // print even numbers
    partitioned.get(true).forEach(System.out::println);
    // do something else with the rest of the set (odd numbers)
    doSomethingElse(partitioned.get(false))
    

    Updated:

    Scala version of the code above

    val set = Set(1, 2, 3, 4, 5)
    val partitioned = set.partition(_ % 2 == 0)
    partitioned._1.foreach(println)
    doSomethingElse(partitioned._2)`
    

提交回复
热议问题