- Java Map集合逻辑方法
分组、List转Map
import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.StudentPlus;
import lombok.Data;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
public class Test100 {
public static void main(String[] args) {
// 1.使用Lambda给List中相同的一个字段进行分组, 结果赋值Map集合中
// 案例:根据key判断优惠卷是否可用返回客户端 ----》可使用、map.get("!可使用").key;
StudentPlus studentPlus01 = new StudentPlus(1, "张三", new Date());
StudentPlus studentPlus00 = new StudentPlus(1, "靳露", new Date());
StudentPlus studentPlus02 = new StudentPlus(2, "李四", new Date());
List<StudentPlus> arrayList = new ArrayList<>();
Collections.addAll(arrayList, studentPlus01, studentPlus00, studentPlus02);
// 逻辑开始
Map<Integer, List<StudentPlus>> collect = arrayList.stream().collect(Collectors.groupingBy(StudentPlus::getId)); //根据Id进行分组
collect.forEach((key, value) -> System.out.println("key: " + key + "; value: " + JSON.toJSON(value)));
/*TODO: key: 1; value: [{"date":1627614007999,"name":"张三","id":1},{"date":1627614007999,"name":"靳露","id":1}]
key: 2; value: [{"date":1627614007999,"name":"李四","id":2}]*/
// 2.把StudentPlus实体类的值转换为Map集合, 然后通过map.key获取员工姓名
Map<Integer, String> map = arrayList.stream().collect(Collectors.toMap(StudentPlus::getId, StudentPlus::getName));
Arrays.stream("1,2".split(",")).forEach(item -> System.out.println("员工名称: " + map.get(Integer.valueOf(item))));
/*TODO: {1=靳露, 2=李四} 员工名称: 靳露 员工名称: 李四*/
}
}
@Data
class Producer {
private String name;
private BigDecimal mony;
public Producer(String name, BigDecimal mony) {
this.name = name;
this.mony = mony;
}
}