Java8 Stream操做

 map( )  处理管道中数据java

@Test
    public void testJava8Stream() throws Exception {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "aaa"));
        userList.add(new User(2, "bbb"));
        userList.add(new User(3, "ccc"));
        User user = new User();

        // lambda 表达式写法
        List<String> list1 = userList.stream()
                .map(e -> e.getUsername()).collect(Collectors.toList());
        // 对象方法引用写法
        List<String> list2 = userList.stream()
                .map(User::getUsername).collect(Collectors.toList());
        // 对象集合的 过滤、排序
        List<User> list3 = userList.stream()
                .filter(e -> e.getUsername().equals("aaa"))
                .sorted((a, b) -> a.getId().compareTo(b.getId()))
                .collect(Collectors.toList());
        // A对象集合 转换成B对象集合
        List<UserInfoDto> list4 = userList.stream()
                .map(u -> BeanCopy.of(u, new UserInfoDto())
                        .copy(BeanUtils::copyProperties)
                        .get())
                .collect(Collectors.toList());

    }

规约 collect(Collectors) 对象集合转换 Map对象ide

//写法一: key-序号Id, value-用户名
        Map<Long, String> map1 = userList.stream()
                .collect(Collectors.toMap(User::getId, User::getUsername));
        // 写法二:key-序号Id,value-User对象
        Map<Long, User> map2 = userList.stream()
                .collect(Collectors.toMap(User::getId, u -> user));
        // 写法三: 未u -> user,lambda 表达式的省略写法,一样为:老是把传入的参数做为返回值返回
        Map<Long, User> map3 = userList.stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

中间操做sorted() 排序 比较器 Comparator用法code

public void test1() {
    List<String> list = Arrays.asList("a", "b", "c", "d", "e");
    List<User> userList = new ArrayList<>();
    userList.add(new User(1, "aaa"));
    userList.add(new User(2, "bbb"));
    userList.add(new User(3, "ccc"));

    // 流操做 升序排列 1
    list.stream().sorted(Comparator.comparing(e -> e))
            .collect(Collectors.toList()).forEach(System.out::println);

    // 流操做 自定义对象 升序排列 2
    userList.stream().sorted(Comparator.comparing(User::getGender))
            .collect(Collectors.toList()).forEach(System.out::println);

    // 自定义排列
    userList.stream().sorted((a, b) -> a.getGender().compareTo(b.getGender()))
            .collect(Collectors.toList()).forEach(System.out::println);
}

中间操做 - distinct 滤重对象

相关文章
相关标签/搜索