3.04-Java技術點小記

一、Stream流的使用

    1.1、分組

    Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId)); 

    1.2、List轉Map

    /**
     * List -> Map
     * 需要注意的是:
     * toMap 如果集合對象有重複的key,會報錯Duplicate key ....
     *  apple1,apple12的id都爲1。
     *  可以用 (k1,k2)->k1 來設置,如果有重複的key,則保留key1,捨棄key2
     */
    Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

    1.3、過濾Filter    : 從集合中過濾出來符合條件的元素

List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

    1.4、求和

    BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

    1.5、最大值 最小值

Dish maxDish = Dish.menu.stream().collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories))).get();//獲取最大值的對象
     Dish minDish = Dish.menu.stream().collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories))).get(); //獲取最小值的對象

    1.6、去重

List<Person> unique = appleList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new));

    1.7、並行流:parallelStream 排序會亂序

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    numbers.parallelStream().forEach(num->System.out.println(num));

    輸出:3 4 2 6 7 9 8 1 5

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章