java8 stream流对数据的操作

stream对数据的操作

    • 一、先初始化数据
    • 二、对list数据进行分组
    • 二、对list数据进行去重

一、先初始化数据

public static List getData(){
        List users = new ArrayList<>(16);
        User user1 = new User("1", "lk1", "123456");
        User user2 = new User("2", "lk2", "123456");
        User user3 = new User("3", "lk2", "123456");
        User user4 = new User("4", "lk4", "123456");
        User user5 = new User("5", "lk5", "123456");
        User user6 = new User("6", "lk6", "123456");
        User user7 = new User("7", "lk2", "123456");
        User user8 = new User("7", "lk2", "123456");
        users.add(user1);users.add(user2);users.add(user3);users.add(user4);
        users.add(user5);users.add(user6);users.add(user7);users.add(user8);
        return users;
    }

二、对list数据进行分组

//1.对list数据进行分组,使用stream流进行操作
    public static void getGroupBy(){
        List data = getData();
        //对用户名进行分组
        Map> collect = data.stream().collect(Collectors.groupingBy(User::getUsername));
        System.out.println(collect);
    }

二、对list数据进行去重

//2.对list数据进行去重
    public static  void getByDistinct(){
        List data = getData();
        List collect = data.stream().distinct().collect(Collectors.toList());
        System.out.println(collect.size());
    }

你可能感兴趣的:(JAVA基础,idea)