import com.alibaba.fastjson.JSON; import lombok.Data; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @ClassName Test * @Description * @Author csg * @Data 2023/4/25 21:31 * @Version 1.0 */ public class Test { public static void main(String[] args) { User user1 = new User("zhangsan", "beijing", "男", 10); User user2 = new User("zhangsan", "beijing", "女", 20); User user3 = new User("lisi", "shanghai", "男", 30); List<User> list = new ArrayList<>(); list.add(user1); list.add(user2); list.add(user3); //先按照名称分组,再按照地址分组,最后按照性别分组 Map<String, Map<String, Map<String, List<User>>>> collect = list.stream().collect( Collectors.groupingBy(User::getSex, Collectors.groupingBy( User::getAddress, Collectors.groupingBy(User::getName) ) ) ); System.out.println(JSON.toJSONString(collect)); } } @Data class User { private String name; private String address; private String sex; private int age; public User(String name, String address, String sex, int age) { this.name = name; this.address = address; this.sex = sex; this.age = age; } }
标签:java,String,stream,list,groupingBy,User,import From: https://www.cnblogs.com/csgbpd/p/17354054.html