如何将任意属性分组的通用List转换成Map?
- 内容介绍
- 文章标签
- 相关推荐
本文共计437个文字,预计阅读时间需要2分钟。
例如,根据姓名和年龄以及班级,三个属性相同的学生分为一组,只需在参数中输入对应的属性名即可。Java版本需使用Java 8+。
数据多属性分组,进行List转Map分组的代码如下:
javaimport java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class GroupByAttributes { public static void main(String[] args) { List students=List.of( new Student(Alice, 20, A), new Student(Bob, 21, B), new Student(Alice, 20, A), new Student(Charlie, 22, B), new Student(Bob, 21, A) );
Map
System.out.println(groupedStudents); }
static class Student { private String name; private int age; private String grade;
public Student(String name, int age, String grade) { this.name=name; this.age=age; this.grade=grade; }
public String getName() { return name; }
public int getAge() { return age; }
public String getGrade() { return grade; }
@Override public String toString() { return Student{ + name=' + name + '\'' + , age= + age + , grade=' + grade + '\'' + '}'; } }}
例如根据 名字和年龄还有班级 三个属性相同的分为一组 ,只需要在参数中输入对应的属性名即可,java版本要求6+/** *
根据多属性进行list转map分组
* * @param list 要转换的集合 shout to LDF * @param strings 作为key的string数组 * @param本文共计437个文字,预计阅读时间需要2分钟。
例如,根据姓名和年龄以及班级,三个属性相同的学生分为一组,只需在参数中输入对应的属性名即可。Java版本需使用Java 8+。
数据多属性分组,进行List转Map分组的代码如下:
javaimport java.util.List;import java.util.Map;import java.util.stream.Collectors;
public class GroupByAttributes { public static void main(String[] args) { List students=List.of( new Student(Alice, 20, A), new Student(Bob, 21, B), new Student(Alice, 20, A), new Student(Charlie, 22, B), new Student(Bob, 21, A) );
Map
System.out.println(groupedStudents); }
static class Student { private String name; private int age; private String grade;
public Student(String name, int age, String grade) { this.name=name; this.age=age; this.grade=grade; }
public String getName() { return name; }
public int getAge() { return age; }
public String getGrade() { return grade; }
@Override public String toString() { return Student{ + name=' + name + '\'' + , age= + age + , grade=' + grade + '\'' + '}'; } }}
例如根据 名字和年龄还有班级 三个属性相同的分为一组 ,只需要在参数中输入对应的属性名即可,java版本要求6+/** *

