Java 集合List转 Map 和Map转List的方法总结(举例说明!)
最近遇到了一个场景是,要将从数据库中查出的List<bean>转换为List<map>然后再取map中的value,最后把所有的value写到Excel中。由于这个bean的属性太多了,我最开始没有采用list转map的方式取获取value,而是在for循环中,写了大量的get方法,导致代码量太高。当然处理这个问题不用poi而选用easyexcel应该是更简单的选择。不过抛开这个不说,虽然走了一些弯路,但List转 Map 和Map转List的方法还是应该总结一下的。
一、List转Map
①、当是list<String>时:(就List内不是存放一个对象时)
比如要实现将从数据库中查出的字符串按照长度进行分组,并返回给前端
(这里我就往list中插入几个数据,进行模拟)
List<String> list = new ArrayList<>();
list.add("hello");
list.add("word");
list.add("come");
list.add("on");
list.add("");
list.add(" ");
list.add(null);
for(String s:list){
System.out.println(s);
}
Map<Integer, List<String>> ans = new HashMap<>();
for(String str: list) {
if(str != null) { //增加非空判断
List<String> sub = ans.get(str.length());
if (sub == null) {
sub = new ArrayList<>();
ans.put(str.length(), sub);
}
sub.add(str);
}
}
System.out.println(ans);
当然代码还可以优化一下:(这样的代码简洁性确实提高了,不过代码的可读性不高,实际场景下也不太会这样写)。
for(String str: list) {
if(str != null) { //增加非空判断
List<String> sub = ans.computeIfAbsent(str.length(), k -> new ArrayList<>());
sub.add(str);
}
}
不过还是解释一下这段代码:
computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) 是一个Map的方法,用于计算Map中的Value。 如果Key已经存在,则直接返回对应的Value;如果Key不存在,则使用给定的mappingFunction计算Value并添加到Map中,最后返回Value。 这样做的好处是可以避免手动检查Key是否存在并添加Value,从而简化代码。 因此,List<String> sub = ans.computeIfAbsent(str.length(), k -> new ArrayList<>()); 的意思是: 如果Map中已经包含了指定长度的字符串列表,则直接取出这个列表赋值给sub; 否则就新建一个空列表并把它赋值给sub,并将这个空列表添加到Map中去。
②、当是list<bean>时:(List内是存放一个对象时)
比如要实现将从数据库中查出的对象list,取对象list中的值,并返回给前端
针对这种情况,先创建一个对象
//创建一个list<bean>
List<KeyValue> list33 = new ArrayList<>();
list33.add(new KeyValue(1, "a"));
list33.add(new KeyValue(2, "b"));
list33.add(new KeyValue(3, "c"));
//打印出list<bean>
for(KeyValue item1:list33) {
System.out.print(item1+", ");
}
System.out.println("n***************************"); //换行输出
// 遍历
Map<Integer, String> keyValueMap = new HashMap<>();
for (KeyValue keyValue : list33) {
keyValueMap.put(keyValue.getKey(), keyValue.getValue());
}
keyValueMap.forEach((k, v) -> System.out.println(k + " ==> " + v));
System.out.println("n***************************"); //换行输出
// Java8 Stream
Map<Integer, String> map = list33.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue));
map.forEach((k, v) -> System.out.println(k + " ==> " + v));
还可有这种思路写法:(当时这个对象属性太多,实际情况还是不要这样写),写的思路可以简述为:(这其实都可以归到 List<Bean>转List<String>了)将搜索得到的List<Bean>转化为List<Map<String, String>>再
转换成一个List<String>
。具体来说,首先对于列表中的每个元素,也就是一个Map<String, String>
,将其所有的键值对取出来。然后对于每个键值对,即Map.Entry<String, String>
,只取它的值,也就是entry.getValue()
,并加入valueList
中。最终得到的valueList
即是所有字符串值的列表。
// 从数据库ensure表中读取数据
List<Salary> userList = staffMapper.getAllStaff(year, month);
log.info("数据为:n{}", userList);
List<Map<String, String>> salaryList = new ArrayList<>();
for (Salary salary : userList) {
Map<String, String> salaryMap = new LinkedHashMap<>();
salaryMap.put("userName", salary.getUserName());
salaryMap.put("firstDepart", salary.getFirstDepart());
salaryMap.put("secondDepart", salary.getSecondDepart());
salaryMap.put("post", salary.getPost());
salaryMap.put("idNumber", salary.getIdNumber());
salaryMap.put("cardNumber", salary.getCardNumber());
salaryMap.put("basicSalary", salary.getBasicSalary());
salaryMap.put("rankSalary", salary.getRankSalary());
salaryMap.put("performSalary", salary.getPerformSalary());
salaryMap.put("subsidy", salary.getSubsidy());
salaryMap.put("overtimeDay", salary.getOvertimeDay());
salaryMap.put("subsidyMeal", salary.getSubsidyMeal());
salaryMap.put("fullDay", salary.getFullDay());
salaryMap.put("compassLeave", salary.getCompassLeave());
salaryMap.put("sickLeave", salary.getSickLeave());
salaryMap.put("actualDay", salary.getActualDay());
salaryMap.put("basePay", salary.getBasePay());
salaryMap.put("rankPay", salary.getRankPay());
salaryMap.put("performPay", salary.getPerformPay());
salaryMap.put("performSubsidy", salary.getPerformSubsidy());
salaryMap.put("performDeduct", salary.getPerformDeduct());
salaryMap.put("illegalDeduct", salary.getIllegalDeduct());
salaryMap.put("confidSubsidy", salary.getConfidSubsidy());
salaryMap.put("bonus", salary.getBonus());
salaryMap.put("fine", salary.getFine());
salaryMap.put("totalPay", salary.getTotalPay());
salaryMap.put("retire", salary.getRetire());
salaryMap.put("medicalLive", salary.getMedicalLive());
salaryMap.put("unemploy", salary.getUnemploy());
salaryMap.put("housing", salary.getHousing());
salaryMap.put("childrenDeduct", salary.getChildrenDeduct());
salaryMap.put("educatDeduct", salary.getEducatDeduct());
salaryMap.put("housingDeduct", salary.getHousingDeduct());
salaryMap.put("rentalDeduct", salary.getRentalDeduct());
salaryMap.put("supportDeduct", salary.getSupportDeduct());
salaryMap.put("careDeduct", salary.getCareDeduct());
salaryMap.put("personalTax", salary.getPersonalTax());
salaryMap.put("actualPay", salary.getActualPay());
salaryMap.put("socialUnitpart", salary.getSocialUnitpart());
salaryMap.put("amonthlySalary", salary.getAmonthlySalary());
salaryMap.put("achieveBonus", salary.getAchieveBonus());
salaryMap.put("status", Integer.valueOf(103).equals(salary.getStatus()) ? "已确认" : "未确认");
salaryMap.put("evidence", salary.getEvidence());
salaryList.add(salaryMap);
}
//取出map键值对中的value值
List<String> valueList = new ArrayList<>();
for (Map<String, String> salaryMap : salaryList) {
Set<Map.Entry<String, String>> entrySet = salaryMap.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
valueList.add(entry.getValue());
}
}
二、Map转List (这里只写了转List<bean>)
Map<Integer, String> map33 = new HashMap<>();
map33.put(1, "a");
map33.put(2, "b");
map33.put(3, "c");
// key 转 List
List<Integer> keyList = new ArrayList<>(map33.keySet());
List<Integer> keyList2 = map33.keySet().stream().collect(Collectors.toList());
keyList.forEach(System.out::println);
keyList2.forEach(System.out::println);
// value 转 List
List<String> valueList = new ArrayList<>(map33.values());
List<String> valueList2 = map33.values().stream().collect(Collectors.toList());
valueList.forEach(System.out::println);
valueList2.forEach(System.out::println);
// Iterator转List
List<KeyValue> keyValueList = new ArrayList<>();
Iterator<Integer> it = map33.keySet().iterator();
while (it.hasNext()) {
Integer k = (Integer) it.next();
keyValueList.add(new KeyValue(k, map33.get(k)));
}
keyValueList.forEach(System.out::println);
// Java8 Stream
List<KeyValue> list = map33.entrySet().stream().map(c -> new KeyValue(c.getKey(), c.getValue()))
.collect(Collectors.toList());
list.forEach(System.out::println);
如果对map遍历还不是很熟悉的小伙伴可以再复习一下map遍历
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
// Map.keySet遍历
for (Integer k : map.keySet()) {
System.out.println(k + " ==> " + map.get(k));
}
System.out.println("n***************************"); //换行输出
map.keySet().forEach(k -> System.out.println(k + " ==> " + map.get(k)));
System.out.println("n***************************"); //换行输出
// Map.entrySet遍历,推荐大容量时使用
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("n***************************"); //换行输出
map.forEach((key, value) -> System.out.println(key + " ==> " + value));
System.out.println("n***************************"); //换行输出
// Iterator遍历
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("n***************************"); //换行输出
map.entrySet().iterator()
.forEachRemaining(entry -> System.out.println(entry.getKey() + " ==> " + entry.getValue()));
System.out.println("n***************************"); //换行输出
// 遍历values
for (String v : map.values()) {
System.out.println(v);
}
System.out.println("n***************************"); //换行输出
map.values().forEach(System.out::println);
System.out.println("n***************************"); //换行输出
// Java8 Lambda
map.forEach((k, v) -> System.out.println(k + " ==> " + v));