对List数据 分类处理,我们可以使用java8的流操作数据
list.stream().collect(Collectors.groupingBy(Class::getType));
得到的map的key是 type,业务中想要把type 替换为其他的字符串 返回给前端。
//测试数据
List<Student> list = new ArrayList<>();
list.add(new Student(1, "张三三"));
list.add(new Student(1, "李四"));
list.add(new Student(0, "红红"));
list.add(new Student(null, "狗子"));
方法一
//方法一
List<Student> collect = list.stream().filter(student -> student.getSex() != null).collect(Collectors.toList());
Map<Integer, List<Student>> collect1 = list.stream().collect(Collectors.groupingBy(Student::getSex));
Iterator<Map.Entry<Integer, List<Student>>> iterator = collect1.entrySet().iterator();
Map<String, List<Student>> result = new HashMap<>();
while (iterator.hasNext()) {
Map.Entry<Integer, List<Student>> next = iterator.next();
Integer key = next.getKey();
String newKey = "";
if (key == null){
continue;
} else if (key == 0) {
newKey = "女";
} else if (key == 1) {
newKey = "男";
}
result.put(newKey, next.getValue());
}
System.out.println(result);
方法二
/**
*
* @param list 元数据
* @param classifier Student::getSex
* @param mapping key的映射关系
* @param <T> list泛型
* @param <K> 分组依赖属性的类型
* @param <L> 自定义key 的类型, 不能重复
* @return
*/
public static<T, K, L> Map<L, List<T>> ListToMap(List<T> list, Function<? super T, ? extends K> classifier, Map<K, L> mapping){
Map<? extends K, List<T>> collect = list.stream().collect(Collectors.groupingBy(classifier));
Iterator<? extends Map.Entry<? extends K, List<T>>> iterator = collect.entrySet().iterator();
Map<L, List<T>> result = new HashMap<>();
while (iterator.hasNext()) {
Map.Entry<? extends K, List<T>> next = iterator.next();
K key = next.getKey();
List<T> value = next.getValue();
//为了处理value = null
if (mapping.containsKey(key)) {
L l = mapping.get(key);
List<T> ts = result.putIfAbsent(l, value);
if (ts != null && ts != value) {
throw new RuntimeException("自定义类型的映射不可重复");
}
} else {
//不包含则直接跳过
continue;
}
}
return result;
}
List<Student> collect = list.stream().filter(student -> student.getSex() != null).collect(Collectors.toList());
Map<Integer, String> mapping = new HashMap<>();
mapping.put(0, "女");
mapping.put(1, "男");
Map<String, List<Student>> stringListMap = ListToMap(collect, Student::getSex, mapping);
System.out.println(stringListMap);