Summary of Java collection List to Map and Map to List methods (examples!)

        Recently I encountered a scenario where I needed to convert the List<bean> retrieved from the database into a List<map> and then get the values ​​in the map, and finally write all the values ​​into Excel. Since this bean has too many attributes, I did not use the list-to-map method to obtain the value at first. Instead, I wrote a large number of get methods in the for loop, which resulted in too high a code volume. Of course, it should be a simpler choice to use easyexcel instead of poi to deal with this problem. But putting this aside, although some detours have been taken, the methods of converting List to Map and Map to List should still be summarized.

1. List to Map

① When it is list<String>: (when the List does not store an object)

For example, you want to group the strings retrieved from the database according to length and return them to the front end.

(Here I will insert some data into the list for simulation)

    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);

         Of course, the code can also be optimized: (The simplicity of such code is indeed improved, but the readability of the code is not high, and it is unlikely to be written like this in actual scenarios).

for(String str: list) {
   if(str != null) {  //增加非空判断
       List<String> sub = ans.computeIfAbsent(str.length(), k -> new ArrayList<>());
          sub.add(str);
     }
}

But let’s explain this code:

computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) is a Map method used to calculate the Value in the Map. If the Key already exists, the corresponding Value is returned directly; if the Key does not exist, the Value is calculated using the given mappingFunction and added to the Map, and finally the Value is returned. The advantage of this is that you can avoid manually checking whether the Key exists and adding the Value, thereby simplifying the code. Therefore, List<String> sub = ans.computeIfAbsent(str.length(), k -> new ArrayList<>()); means: If the Map already contains a string list of the specified length, take this out directly The list is assigned to sub; otherwise, create an empty list and assign it to sub, and add this empty list to the Map.

②. When it is list<bean>: (when an object is stored in the List)

For example, you want to implement an object list retrieved from the database, take the value in the object list, and return it to the front end.

For this situation, first create an object

//创建一个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));

        You can also write this way of thinking: (At that time, this object had too many attributes, so it is better not to write it like this in reality). The writing idea can be briefly described as: (This can actually be classified as List<Bean> to List<String>) Convert the search result List<Bean>转化为List<Map<String, String>>再into one List<String>. Specifically, first, for each element in the list, that is, one Map<String, String>, all its key-value pairs are taken out. Then for each key-value pair, ie Map.Entry<String, String>, just take its value, ie entry.getValue(), and join valueListin. The end result valueListis a list of all string values.

       // 从数据库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());
            }
        }

 2. Convert Map to List (only converting List<bean> is written here)

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);

If you are not very familiar with map traversal, you can review map traversal again.

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));

 

Guess you like

Origin blog.csdn.net/weixin_49171365/article/details/130928401