1. 程式人生 > >Java 8 Stream partitioningBy對List分割槽

Java 8 Stream partitioningBy對List分割槽

partitioningBy分割槽是一種特殊的分組,可以將List劃分為兩個子List,使用起來比較簡單,如下:

@Test
public void partitionByTest(){
    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);

    Map<Boolean, List<Integer>> groups =
            intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
    List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());

    List<Integer> lastPartition = subSets.get(1);
    List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
    assertThat(subSets.size(), equalTo(2));
    assertThat(lastPartition, equalTo(expectedLastPartition));
}

通過上述的例子看一看出,通過partitionBy將intList劃分為大於6和小於等於6的兩個子List。本來打算跟groupingBy一起寫的,但是覺得這個partitionBy也跟groupingBy一樣有很多示例,結果看了之後才發現是個很簡單的東西 ==