stream — 排序与映射(三)

* map—接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
* FlatMap—接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

    List<Employee> employees = Arrays.asList(//
            new Employee(20, "张三", 5000.35), //
            new Employee(40, "李四", 6500.63), //
            new Employee(30, "王五", 4000.93), //
            new Employee(50, "赵六", 9005.36), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(20, "朱八", 3000.73)//
    );

1、map—接收Lambda,FlatMap—接收一个函数作为参数

    @Test
    public void test5() {
        List<String> asList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff");
        asList.stream().map((e) -> e.toUpperCase()).forEach(System.out::println);

        System.out.println("====================");
        employees.stream().map(Employee::getName).forEach(System.out::println);

        System.out.println("====================");
        Stream<Stream<Character>> map = asList.stream().map(StreamApiTest2::filterCharacter);
        map.forEach((e) -> {
            e.forEach(System.out::println);
        });

        System.out.println("====================");
        asList.stream().flatMap(StreamApiTest2::filterCharacter).forEach(System.out::println);
    }

    private static Stream<Character> filterCharacter(String str) {
        List<Character> list = new ArrayList<Character>();
        char[] charArray = str.toCharArray();
        for (char c : charArray) {
            list.add(c);
        }
        return list.stream();
    }

2、排序 sorted()—自然排序 sorted(Comparator com)一定制排序

    @Test
    public void test6() {
        List<String> asList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff");
        asList.stream().sorted().forEach(System.out::println);

        System.out.println("====================");
        employees.stream().sorted((e1, e2) -> {
            if (e1.getAge().equals(e2.getAge())) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return -e1.getAge().compareTo(e2.getAge());
            }
        }).forEach(System.out::println);
    }

 

posted on 2019-11-14 00:44  牛鼻子老赵  阅读(211)  评论(0编辑  收藏  举报