添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "张三", 10));
        list.add(new Student(2, "李四", 20));
        list.add(new Student(1, "张三", 30));
        Map<Integer, Student> map = new HashMap<>();
        for (Student student : list) {
            Integer id = student.getId();
            if (map.containsKey(id)) {
                Student s = map.get(id);
                s.setAge(s.getAge() + student.getAge());
                map.put(id, s);
            } else {
                map.put(id, student);
        List<Student> studentList = new ArrayList<>();
        for(Integer temp:map.keySet()){
            studentList.add(map.get(temp));
        System.out.println(studentList);
//[StreamTest.Student(id=1, name=张三, age=40), StreamTest.Student(id=2, name=李四, age=20)]

通过java8来实现

        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "张三", 10));
        list.add(new Student(2, "李四", 20));
        list.add(new Student(1, "张三", 30));
        List<Student> studentList = new ArrayList<>();
        list.parallelStream().collect(Collectors.groupingBy(Student::getId, Collectors.toList()))
                .forEach((id, transfer) -> {
                    transfer.stream().reduce((a, b) -> new Student(a.getId(), a.getName(), a.getAge() + b.getAge())).ifPresent(studentList::add);
        System.out.println(studentList);
//[StreamTest.Student(id=1, name=张三, age=40), StreamTest.Student(id=2, name=李四, age=20)]