怎么用Lambda进行分组

Jessica丶 发布于 03/01 15:25
阅读 673
收藏 0

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

Stu里面有3个属性id,name,course,course是学生参加的课程,用逗号隔开,id是Long类型的

Stu stu1 = new Stu(1L,'张三',"1,2");
Stu stu2 = new Stu(2L,'李四',"2,3");
Stu stu3 = new Stu(3L,'王五',"4");
List<Stu> list = new ArrayList();
list.add(stu1);
list.add(stu2);
list.add(stu3);

现在需要将上面的list转换成Map<Long,List<Long>>类型的,即要获取到每个学生参加的课程

返回{1=[1, 2], 2=[2, 3], 3=[4]},这样的用Lambda怎么实现

加载中
0
k
kekeke1
list.stream().collect(Collectors.toMap(Stu::getId, stuVal-> Arrays.stream(stuVal.getCourse().split(",")).map(Long::parseLong).collect(Collectors.toList())));
0
osc_07527084
osc_07527084
Student stu1 = new Student(1, "张三", "1,2");
Student stu2 = new Student(2, "李四", "2,3");
Student stu3 = new Student(3, "王五", "4");
List<Student> list = new ArrayList();
list.add(stu1);
list.add(stu2);
list.add(stu3);
Map<Integer, List<String>> collect = list.stream().collect(Collectors.toMap(Student::getId, student -> {
  String[] split = student.getCourse().split(",");
  return Arrays.asList(split);
}, (a, b) -> a));
System.out.println(collect);
0
osc_07527084
osc_07527084
Student stu1 = new Student(1, "张三", "1,2");
Student stu2 = new Student(2, "李四", "2,3");
Student stu3 = new Student(3, "王五", "4");
List<Student> list = new ArrayList();
list.add(stu1);
list.add(stu2);
list.add(stu3);
Map<Integer, List<Integer>> collect = list.stream()
                                .collect(Collectors.toMap(Student::getId,
                                                   student -> {
                                                     String[] split = student.getCourse().split(",");
                                                     return Arrays.stream(split)
                                                               .map(Integer::parseInt)
                                                               .collect(
                                                                  Collectors.toList());
                                                   }, (a, b) -> a));
System.out.println(collect);
0
osc_98982162
osc_98982162
Map<Long, List<Long>> listMap = list.stream().collect(Collectors.toMap(
        Stu::getId,
        stu -> {
           return Arrays.stream(stu.getCourse().split(",")).map(Long::parseLong).collect(Collectors.toList());
        }
));
0
ducat7
ducat7
Object[] stu_1 = {1L, "张三", "1,2"};
Object[] stu_2 = {2L, "李四", "2,3"};
Object[] stu_3 = {3L, "王五", "4"};
List<Object[]> list = new ArrayList();
list.add(stu_1);
list.add(stu_2);
list.add(stu_3);

// 获取 每个学生参加的课程,即:{1=[1, 2], 2=[2, 3], 3=[4]}
Map<Long, List<Long>> group = list.stream().collect(Collectors.toMap(stu -> (Long) stu[0]
      , stu -> Arrays.stream(stu[2].toString().split(","))
            .map(Long::parseLong)
            .collect(Collectors.toList())
      , (old, now) -> {
         old.addAll(now);
         return old;
      }
));
System.out.println(group);
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部
返回顶部
顶部