Sorting collection of maps based on values [closed]

不打扰是莪最后的温柔 提交于 2020-11-30 01:58:04

问题


I'm trying to sort list of maps based on specific key lets say "tax" with int values in all the maps. However other keys like "id" and "price" have string and double type values respectively as shown below.

List<Map<String, Object>> taxes = Arrays.asList(Map.of("id", "3", "tax", 25, "price", 8.05),
            Map.of("id", "9", "tax", 37, "price", 16.05), Map.of("id", "2", "tax", 19, "price", 9.25),
            Map.of("id", "11", "tax", 28, "price", 16.05));

I want to sort list of maps with highest tax value to lowest tax value. I'm trying with below approach but getting error at m.get("tax").

list.stream()
    .sorted(Comparator.comparing(map -> map.get("tax")).reversed())
    .collect(Collectors.toList());`

回答1:


You are getting the error because compile could not interpret the type of object in a lambda expression, you can solve it but just interpreting map as Map<String, Integer>

list.stream()
.sorted(Comparator.comparing((Map<String,Integer> map) -> map.get("tax")).reversed())
.collect(Collectors.toList());

But this is not completely fixed and it will fail when tax is not presenting in any Map or having null as value, you can solve that using Comparator.nullsFirst or Comparator.nullsLast

List<Map<String,Integer>> taxes = List.of(Map.of("id",3, "tax",25),
            Map.of("id",9, "tax",37),Map.of("id",2, "tax",19),
            Map.of("id",11));

List<Map<String,Integer>> results = taxes.stream()
            .sorted(Comparator.comparing((Map<String,Integer> map)->map.get("tax"),Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
            .collect(Collectors.toList());

 System.out.println(results);   //[{tax=37, id=9}, {tax=25, id=3}, {tax=19, id=2}, {id=11}]


来源:https://stackoverflow.com/questions/64975372/sorting-collection-of-maps-based-on-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!