java8函数式编程(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/litte_frog/article/details/82972047

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”
备注:尽量避免使用下面1的书写方式,可以考虑2

1:	Frog frog =	init().stream()
                .filter(frog -> frog.getAge() > 6)
                .findFirst()
                .orElse(null);
    if (frog != null){
		// 业务处理;
	}
2:	init().stream()
                .filter(frog -> frog.getAge() > 6)
                .findFirst()
                .isPresent( e -> { // 业务处理; });

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}]}

猜你喜欢

转载自blog.csdn.net/litte_frog/article/details/82972047