本文介绍了转换List< Object>到Map< String,Integer>这样使用Java 8 Streams字符串就不会是重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有一个Student
类,如下所示:
We have a Student
class as follows:
class Student {
private int marks;
private String studentName;
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student(String studentName, int marks) {
this.marks = marks;
this.studentName = studentName;
}
}
我们有一个学生名单,如下:
We have a LIST of Students as follows :
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("abc", 30));
studentList.add(new Student("Abc", 32));
studentList.add(new Student("ABC", 35));
studentList.add(new Student("DEF", 40));
此列表需要转换为HashMap<String, Integer>
,以便:
This List needs to be converted into a HashMap<String, Integer>
such that:
- 地图上没有重复的学生
- 如果发现重复的学生姓名,则应在他的标记后加上以前的事件.
- the map does not contain any duplicate Student
- if a duplicate student name is found, his marks shall be added withthe previous occurrence.
因此输出应为:
{ABC = 97, DEF = 40}
我尝试如下解决此问题:
I have tried to solve this issue as follows:
Map<String, Integer> studentMap = studentList.stream()
.collect(Collectors.toMap(
student -> student.getStudentName().toLowerCase(),
student -> student.getMarks(),
(s1, s2) -> s1,
LinkedHashMap::new));
但是merge函数不允许我连接标记,这会将输出返回为:
But the merge function does not allow me to concatenate the marks and this returns the output as:
{abc = 30, DEF = 40}
有人可以为此建议一个有效的解决方案吗?
Can someone suggest an efficient solution for this?
推荐答案
那是因为合并功能不正确,您应该改用:
That's because of an incorrect merge function, you should instead use:
Map<String, Integer> map = studentList.stream()
.collect(Collectors.toMap(
student -> student.getStudentName().toLowerCase(),
Student::getMarks,
(s1, s2) -> s1 + s2, // add values when merging
LinkedHashMap::new));
这篇关于转换List< Object>到Map< String,Integer>这样使用Java 8 Streams字符串就不会是重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!