实体类List中以某字段为key,获取另外一个字段的List

List<Entity>转Map<String, List<Sting>>

为了保证程序的性能,如果要分组查数据库,一般会用到JAVA8 中的

Collection.stream().collect(Collectors.groupingBy(Entity::getXXXX));

得到Map<String, List<Entity>>,但如果想的到的list中存的是Entity里的某个字段时  就需要再次循环遍历获取,感觉有些麻烦,所以在网上找了一些简便写法,整理总结下。

假设有学生信息实体类如下:

@Data
@AllArgsConstructor
@NoArgsConstructor
class StudentInfo {
    /**
     * 姓名
     */
    private String name;
    /**
     * 班级
     */
    private Integer classNum;
}

学生信息有学生信息List如下:

StudentInfo a = new StudentInfo("张三", 1);
StudentInfo b = new StudentInfo("李四", 1);
StudentInfo c = new StudentInfo("王五", 1);
StudentInfo d = new StudentInfo("赵大", 2);
StudentInfo e = new StudentInfo("钱二", 2);
StudentInfo f = new StudentInfo("周六", 3);

List<StudentInfo> studentInfos = new ArrayList<>(Arrays.asList(a, b, c, d, e, f));

想获各个班级下的学生姓名(想要获得效果)

1 : [张三, 李四, 王五]
2 : [赵大, 钱二]
3 : [周六]

首先能想到的写法如下 JAVA8中的 Collectors.groupingBy:

public static void main(String[] args) {
	StudentInfo a = new StudentInfo("张三", 1);
	StudentInfo b = new StudentInfo("李四", 1);
	StudentInfo c = new StudentInfo("王五", 1);
	StudentInfo d = new StudentInfo("赵大", 2);
	StudentInfo e = new StudentInfo("钱二", 2);
	StudentInfo f = new StudentInfo("周六", 3);

	List<StudentInfo> studentInfos = new ArrayList<>(Arrays.asList(a, b, c, d, e, f));

	Map<Integer, List<StudentInfo>> collect = studentInfos.stream().collect(Collectors.groupingBy(StudentInfo::getClassNum));
	Map<Integer, List<String>> class2Name = new HashMap<>();
	for (int i : collect.keySet()) {
		List<String> collect1 = collect.get(i).stream().map(StudentInfo::getName).collect(Collectors.toList());
		class2Name.put(i, collect1);
	}
	class2Name.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
}

总感觉应该还有高级写法,在网上寻找后,发现如下写法

使用 JAVA8 中的 computeIfAbsent

public static void main(String[] args) {
	StudentInfo a = new StudentInfo("张三", 1);
	StudentInfo b = new StudentInfo("李四", 1);
	StudentInfo c = new StudentInfo("王五", 1);
	StudentInfo d = new StudentInfo("赵大", 2);
	StudentInfo e = new StudentInfo("钱二", 2);
	StudentInfo f = new StudentInfo("周六", 3);

	List<StudentInfo> studentInfos = new ArrayList<>(Arrays.asList(a, b, c, d, e, f));

	Map<Integer, List<String>> stuMap1 = new HashMap<>();
	studentInfos.forEach(studentInfo -> stuMap1.computeIfAbsent(studentInfo.getClassNum(), ArrayList::new).add(studentInfo.getName()));
	stuMap1.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
}

使用JAVA8中的 Collectors.toMap

public static void main(String[] args) {
	StudentInfo a = new StudentInfo("张三", 1);
	StudentInfo b = new StudentInfo("李四", 1);
	StudentInfo c = new StudentInfo("王五", 1);
	StudentInfo d = new StudentInfo("赵大", 2);
	StudentInfo e = new StudentInfo("钱二", 2);
	StudentInfo f = new StudentInfo("周六", 3);

	List<StudentInfo> studentInfos = new ArrayList<>(Arrays.asList(a, b, c, d, e, f));

	Map<Integer, List<String>> stuMap = studentInfos.stream()
			.collect(Collectors.toMap(StudentInfo::getClassNum, x -> Lists.newArrayList(x.getName()), (objects, objects2) -> {
				objects.addAll(objects2);
				return objects;
			}));
	stuMap.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
	System.out.println("-----------------------------------");


	Map<Integer, List<String>> stuMap2 = studentInfos.stream()
			.collect(Collectors.toMap(StudentInfo::getClassNum, x -> new ArrayList<>(Collections.singletonList(x.getName())), (objects, objects2) -> {
				objects.addAll(objects2);
				return objects;
			}));
	stuMap2.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
}

附上整个测试代码:

package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.stream.Collectors;

public class List2MapTest {

    public static void main(String[] args) {
        StudentInfo a = new StudentInfo("张三", 1);
        StudentInfo b = new StudentInfo("李四", 1);
        StudentInfo c = new StudentInfo("王五", 1);
        StudentInfo d = new StudentInfo("赵大", 2);
        StudentInfo e = new StudentInfo("钱二", 2);
        StudentInfo f = new StudentInfo("周六", 3);

        List<StudentInfo> studentInfos = new ArrayList<>(Arrays.asList(a, b, c, d, e, f));

        /*studentInfos.add(a);
        studentInfos.add(b);
        studentInfos.add(c);
        studentInfos.add(d);
        studentInfos.add(e);
        studentInfos.add(f);*/

        Map<Integer, List<String>> stuMap1 = new HashMap<>();
        studentInfos.forEach(studentInfo -> stuMap1.computeIfAbsent(studentInfo.getClassNum(), ArrayList::new).add(studentInfo.getName()));
        stuMap1.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
        System.out.println("-----------------------------------");


        Map<Integer, List<String>> stuMap = studentInfos.stream()
                .collect(Collectors.toMap(StudentInfo::getClassNum, x -> Lists.newArrayList(x.getName()), (objects, objects2) -> {
                    objects.addAll(objects2);
                    return objects;
                }));
        stuMap.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
        System.out.println("-----------------------------------");


        Map<Integer, List<String>> stuMap2 = studentInfos.stream()
                .collect(Collectors.toMap(StudentInfo::getClassNum, x -> new ArrayList<>(Collections.singletonList(x.getName())), (objects, objects2) -> {
                    objects.addAll(objects2);
                    return objects;
                }));
        stuMap2.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
        System.out.println("-----------------------------------");


        Map<Integer, List<StudentInfo>> collect = studentInfos.stream().collect(Collectors.groupingBy(StudentInfo::getClassNum));
        System.out.println(JSON.toJSON(collect));

        Map<Integer, List<String>> class2Name = new HashMap<>();
        for (int i : collect.keySet()) {
            List<String> collect1 = collect.get(i).stream().map(StudentInfo::getName).collect(Collectors.toList());
            class2Name.put(i, collect1);
        }
        class2Name.forEach((integer, stringList) -> System.out.println(integer + " : " + stringList));
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class StudentInfo {
    /**
     * 姓名
     */
    private String name;
    /**
     * 班级
     */
    private Integer classNum;
}

 

最后再附上要用到的依赖

<!--compile('org.projectlombok:lombok:1.16.12')-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.16.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.49</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>26.0-jre</version>
</dependency>

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值