1. 程式人生 > >java8函數語言程式設計(二)

java8函數語言程式設計(二)

List常用操作

準備資料

    private static List<Frog> init() {
        List<Frog> list = new ArrayList<>();
        list.add(new Frog("a", 2 , "red", 5.1));
        list.add(new Frog("b", 3 , "red", 5.0));
        list.add(new Frog("c", 2 , "blue", 5.5));
        list.add(new Frog("d", 1 , "blue"
, 5.3)); list.add(new Frog("e", 5 , "yellow", 5.1)); list.add(new Frog("f", 3 , "yellow", 5.2)); return list; }

forEach

迴圈列印集合中每個元素

    private static void foreach() {
        //init().forEach(t -> System.out.println(t));
        init().forEach(System.out::println);
    }

toList

    private static void toList() {
        List<String> list = Stream.of("a", "b", "c")
                .collect(Collectors.toList());
        System.out.println(list);
    }

filter

計算集合中age>4的元素個數

    private static void filter() {
        long count = init().stream()
                .
filter(frog -> frog.getAge() < 4) .count(); System.out.println(count); }

篩選出顏色為blue的元素

    private static void filter() {
        // 1
        List<Frog> list = init().stream()
                .filter(frog -> "blue".equals(frog.getColor()))
                .collect(Collectors.toList());
        System.out.println(list);
        // 2
        List<Frog> frogs = init();
        frogs.removeIf(frog -> !"blue".equals(frog.getColor()));
        System.out.println(frogs);
    }

map

將集合中元素name重新組合為一個集合

    private static void map() {
        List<String> nameList = init().stream()
                .map(Frog::getName)
                .collect(Collectors.toList());
        System.out.println(nameList);
    }

max

集合中size最大的元素

    private static void max() {
        Frog frog = init().stream()
                .max(Comparator.comparingDouble(Frog::getSize))
                .get();
        System.out.println(frog);
    }

reduce

對集合中元素的age求和

    private static void reduce() {
        int value = init().stream()
                .mapToInt(Frog::getAge)
                .reduce(0, (x, y) -> x + y);
        System.out.println(value);
    }

flatMap

使用flatMap將多個stream合併為一個stream

    private static void flatMap() {
        List<Cool> cools = new ArrayList<>();
        cools.add(new Cool("cool1", init()));
        cools.add(new Cool("cool2", init()));

        Set<String> set = new HashSet<>();
        for (Cool cool: cools) {
            for (Frog frog: cool.getList()) {
                if (frog.getAge() > 4) {
                    set.add(frog.getName());
                }
            }
        }
        System.out.println(set);

        
        Set<String> set1 = cools.stream()
                .flatMap(cool -> cool.getList().stream())
                .filter(frog -> frog.getAge() > 4)
                .map(Frog::getName)
                .collect(Collectors.toSet());
        System.out.println(set1);
    }

Optional

isPresent 該方法表示一個Optional 物件裡是否有值 orElse 當Optional 物件為空時,該方法提供一個備選值 orElseGet 方法適用當備選值在計算上繁瑣時使用 empty和ofNullable為工廠方法,可將一個空值轉換成Optional 物件

    private static void optional() {
        Frog frog1 = init().stream()
                .filter(frog -> frog.getAge() > 6)
                .findFirst()
                .orElseGet(Frog::new);
        System.out.println(frog1);

        String str = init().stream()
                .filter(frog -> frog.getAge() > 6)
                .map(Frog::getName)
                .findFirst()
                .orElse("is null");
        System.out.println(str);
    }

如果為空建立一個新物件;如果為空列印“is null”

Collectors

    private static void collect() {
        // 按顏色分組
        Map<String, List<Frog>> map = init().stream()
                .collect(Collectors.groupingBy(Frog::getColor));
        System.out.println(map);

        // 將名稱按指定格式拼接成字串
        String str = init().stream()
                .map(Frog::getName)
                .collect(Collectors.joining("、","{","}"));
        System.out.println(str);

        // 每種顏色的數量
        Map<String, Long> map1 = init().stream()
                .collect(Collectors.groupingBy(Frog::getColor, Collectors.counting()));
        System.out.println(map1);

        // 每種顏色中的名稱
        Map<String, List<String>> map2 = init().stream()
                .collect(Collectors.groupingBy(
                        Frog::getColor,
                        Collectors.mapping(Frog::getName, Collectors.toList())));
        System.out.println(map2);

        // 每種顏色中的size最大元素
        Map<String, Optional<Frog>> map3 = init().stream()
                .collect(Collectors.groupingBy(
                        Frog::getColor,
                        Collectors.maxBy(Comparator.comparingDouble(Frog::getSize))));
        System.out.println(map3);
    }

執行結果

{red=[Frog{name='a', age=2, color='red', size=5.1}, Frog{name='b', age=3, color='red', size=5.0}], blue=[Frog{name='c', age=2, color='blue', size=5.5}, Frog{name='d', age=1, color='blue', size=5.3}], yellow=[Frog{name='e', age=5, color='yellow', size=5.1}, Frog{name='f', age=3, color='yellow', size=5.2}]}
{a、b、c、d、e、f}
{red=2, blue=2, yellow=2}
{red=[a, b], blue=[c, d], yellow=[e, f]}
{red=Optional[Frog{name='a', age=2, color='red', size=5.1}], blue=Optional[Frog{name='c', age=2, color='blue', size=5.5}], yellow=Optional[Frog{name='f', age=3, color='yellow', size=5.2}]}