Partition the input list into two lists - Java Lambda Stream

Java examples for Lambda Stream:Predicate

Description

Partition the input list into two lists

Demo Code

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

public class Main {

  public static <T> Map<Boolean, List<T>> partition(List<T> list, Predicate<? super T> p) {
    // The result should be equivalent to the code:
    // list.stream().collect(Collectors.partitoningBy(p)) ;
    Map<Boolean, List<T>> rlt = new HashMap<>();
    List<T> t = new ArrayList<>();
    List<T> f = new ArrayList<>();
    list.forEach(h -> {/* w  w w.  ja v  a2s .  c o  m*/
      if (p.test(h)) {
        t.add(h);
      } else {
        f.add(h);
      }
    });
    rlt.put(Boolean.TRUE, t);
    rlt.put(Boolean.FALSE, f);
    return rlt;
  }
}

Related Tutorials