昨天写代码的时候,遇到了如题的业务场景,一开始是用的笨方法(下方代码中有描述),一不注意 还搞了个死循环,后来项目组的二宝看了下说你可以用 stream 流,一行代码就可以了。对啊,先前用过,忘求了。
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.*;
import java.util.stream.Collectors;
public class ListGroupBy {
/**
* 取出集合中目标值放入一个 set(去重) 中,
* 然后迭代 set 取值再与对象的具体值进行比较,
* 匹配后放入集合,最后组装成 map 返回
*
* @param list
* @return {@link Map}<{@link String}, {@link Object}>
*/
private static Map<String, Object> transform(List<Student> list) {
Map<String, Object> resultMap = new HashMap<>();
Set<Object> setTmp = new HashSet<>();
// 循环 list 取出靶子值,放入 set
for (Student student : list) {
setTmp.add(student.getGrade()); // 按照年级分组
}
Iterator<Object> it = setTmp.iterator();
while (it.hasNext()) {
String targetGradeStr = (String) it.next();
List<Student> oneSetTmpList = new ArrayList<>();
// 再次循环 list ,取出相应字段与靶子值比较
for (Student tmp : list) {
String grade = tmp.getGrade();
if (targetGradeStr.equals(grade)) {
oneSetTmpList.add(tmp);
}
}
resultMap.put(targetGradeStr, oneSetTmpList);
}
return resultMap;
}
public static void main(String[] args) {
List<Student> inList = new ArrayList<>();
Student stu1 = new Student("小黑", 18, "一");
Student stu2 = new Student("蓝胖", 22, "二");
Student stu3 = new Student("小炮", 38, "一");
Student stu4 = new Student("拉比克", 58, "二");
Student stu5 = new Student("人马", 78, "三");
inList.add(stu1);
inList.add(stu2);
inList.add(stu3);
inList.add(stu4);
inList.add(stu5);
System.out.println("原始inList---" + inList);
Map<String, Object> resultMap = transform(inList);
System.out.println("分组后---" + resultMap);
// 更简单的方法是使用 stream
Map<String, List<Student>> collect = inList.stream().collect(Collectors.groupingBy(Student::getGrade));
System.out.println("stream-分组后---" + collect);
}
}
@Data
@AllArgsConstructor
class Student {
private String name;
private int age;
private String grade;
}
(图网,侵删)