使用stream流對List集合分組

直接上代碼

public static void main(String[] args) {
    // 初始化一個List集合
    List<Integer> numberList = Arrays.asList(3, 5, 6, 4, 2, 8, 9, 1, 7);

    //使用stream流進行分組(使用條件)
    Map<Boolean, List<Integer>> splitMap = numberList.stream().collect(Collectors.groupingBy(number -> number < 5));
    // 滿足條件的一組
    List<Integer> trueList = splitMap.get(true);
    // 不滿足條件的一組
    List<Integer> falseList = splitMap.get(false);

    System.out.println(trueList);
    System.out.println(falseList);
}

/*
結果:
		[3, 5, 4, 2, 1]
		[6, 8, 9, 7]
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章