'Group map values but keys are same
I have a map like this. Map<long,List<Student>> studentMap
Key is a number 1,2,3,4... Student object is :
public class Student {
private long addressNo;
private String code;
private BigDecimal tax;
private String name;
private String city;
// getter and setters`
}
What i want to do is to convert it Map<long,List<StudentInfo>> studentInfoMap object and group id, addressNo and code fields.I want key are same for both maps.
I can group the map by using these codes but summingDouble is not working for BigDecimal.Also I cannot convert my studentMap to studentInfoMap.:(
studentInfoMap.values().stream()
.collect(
Collectors.groupingBy(StudentInfo::getCode,
Collectors.groupingBy(StudentInfo::getAddressNo,
Collectors.summingDouble(StudentInfo::getTax))));
My studentInfo object is :
public class StudentInfo {
private long addressNo;
private String code;
private BigDecimal tax;
// getter and setters`
}
Solution 1:[1]
Map<Integer, Object> map = new HashMap<>();
map.put(1, studentInfoMap.values().stream().map(
student -> student.getAddressNo()
).collect(Collectors.toList()));
map.put(2, studentInfoMap.values().stream().map(
student -> student.getCode()
).collect(Collectors.toList()));
// and so ...
Solution 2:[2]
To convert the map from Student to StudentInfo, whilst keeping the same keys, you could do something like this:
Set<Long> keys = studentMap.keySet();
List<Long> keylist = new ArrayList<>(keys);
Map<Long, List<StudentInfo>> studentInfoMap = new HashMap<>();
for(int i = 0; i < keys.size(); i++){
long key = keylist.get(i);
List<Student> list = studentMap.get(key);
List<StudentInfo> result = new ArrayList<>();
// Create the new StudentInfo object with your values
list.forEach(s -> result.add(new StudentInfo(s.name())));
// Put them into the new Map with the same keys
studentInfoMap.put(key, result);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saad Zimat |
| Solution 2 | Denis Müller |
