Search code examples
javajava-8streamjava-stream

Why is it not in the order of key when converting key to uppercase even though I use LinkedHashMap


When I convert to lowercase, it's in the right order. When I try to convert to uppercase,it's wrong. I try to use LinkedHashMap to keeping the insertion order. I think stream changed the order of keys,But I don't know how to sort after changing the key.

Thanks in advance.

Here is my code



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

public class Test {

    static List<Map<String,Object>>  convertKeyCase (List<Map<String,Object>> list,int...s) {

       return list.stream().map(m -> m.entrySet().stream().sorted(Map.Entry.comparingByKey())
               .collect(Collectors.toMap(p -> s.length == 0 || s[0]==1 ? p.getKey().toUpperCase():p.getKey().toLowerCase(), Map.Entry::getValue)))
               .collect(Collectors.toList());

    }
    public static void main(String[] args) {
        List<Map<String,Object>> list1 = new ArrayList<>();

        Map<String,Object> map1 = new LinkedHashMap<>();
        Map<String,Object> map2 = new LinkedHashMap<>();


        map1.put("date","2021-06-03");
        map1.put("weather","1");
        map1.put("wind","2-3");
        map1.put("temp","17-29°C");
        list1.add(map1);

        map2.put("date","2021-06-04");
        map2.put("weather","1");
        map2.put("wind","3-4");
        map2.put("temp","17-30°C");
        list1.add(map2);

        List<Map<String,Object>> list = convertKeyCase(list1);
        List<Map<String,Object>> list2 = convertKeyCase(list1,0);
        System.out.println(list);
        System.out.println(list2);

    }
}



Solution

  • The fact that the input List contains LinkedHashMaps doesn't mean that the output will contain LinkedHashMaps.

    If you want LinkedHashMaps, you must request them explicitly in the toMap() call:

    static List<Map<String,Object>>  convertKeyCase (List<Map<String,Object>> list,int...s) {
    
       return list.stream()
                  .map(m -> m.entrySet()
                             .stream()
                             .sorted(Map.Entry.comparingByKey())
                             .collect(Collectors.toMap(p -> s.length == 0 || s[0]==1 ? p.getKey().toUpperCase():p.getKey().toLowerCase(),
                                                       Map.Entry::getValue,
                                                       (v1,v2)->v1,
                                                       LinkedHashMap::new)))
                  .collect(Collectors.toList());
    
    }
    

    This changes the output to:

    [{DATE=2021-06-03, TEMP=17-29°C, WEATHER=1, WIND=2-3}, {DATE=2021-06-04, TEMP=17-30°C, WEATHER=1, WIND=3-4}]
    [{date=2021-06-03, temp=17-29°C, weather=1, wind=2-3}, {date=2021-06-04, temp=17-30°C, weather=1, wind=3-4}]