Three Realization Methods of Grouping Statistics in java
- 2021-10-16 01:52:55
- OfStack
In normal work, it is often used to group data, for example, a student object with class, name, gender, score, etc., which needs to be counted according to class groups. How to operate? A reasonable algorithm can improve a lot of efficiency.
Let's look at the following case:
// The following is the initialized data
List<Student> list = new ArrayList<Student>();
Student student1 = new Student(" Li 41", " Female ", "1 Class ");
Student student2 = new Student(" Li 42", " Female ", "1 Class ");
Student student3 = new Student(" Li 43", " Female ", "1 Class ");
Student student4 = new Student(" Li 44", " Male ", "1 Class ");
Student student5 = new Student(" Li 45", " Male ", "1 Class ");
Student student6 = new Student(" Li 46", " Male ", "2 Class ");
Student student7 = new Student(" Li 47", " Male ", "2 Class ");
Student student8 = new Student(" Li 48", " Male ", "2 Class ");
Student student9 = new Student(" Li 49", " Male ", "2 Class ");
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
list.add(student6);
list.add(student7);
list.add(student8);
list.add(student9);
1. Reasonable use of map operation
Reasonable use of map's own methods in actual development can solve many problems
for (Student stu : list) {
if (!map.containsKey(stu.getProvinceCode())) {
ArrayList<ArrearageDeal> al = new ArrayList<ArrearageDeal>();
map.put(stu.getProvinceCode(), al.add(stu));
} else {
map.get(stu.getProvinceCode()).add(stu);
}
}
2. Multimap using guava
Multimap<String, Student> mulMap = ArrayListMultimap.create();
for (Student stu : list) {
mulMap.put(stu.getGrade,stu);
}
3. Use the new features of jdk8 without excluding new things
After all, java14 has come out, and the new features of java8 still need to be known more
//1 OK, it can be solved
Map<String, List<Student >> collect = list.stream().collect(Collectors.groupingBy(ArrearageDeal::getGrade));
The above three kinds of code at that time, java8 is the most concise. However, in actual development, combined with specific scenarios, 2 and 3 are both good choices.
Java8 Grouping statistics of multiple fields
// Group statistics
Map<String, Long> countMap = records.stream().collect(Collectors.groupingBy(o -> o.getProductType() + "_" + o.getCountry(), Collectors.counting()));
List<Record> countRecords = countMap.keySet().stream().map(key -> {
String[] temp = key.split("_");
String productType = temp[0];
String country = temp[1];
Record record = new Record();
record.set("device_type", productType);
record.set("location", country;
record.set("count", countMap.get(key).intValue());
return record;
}).collect(Collectors.toList());