面试题:对List分组排序的实现

2019-07-09 21:46:43

题目

小试牛刀

  1. public class SortUtil {
  2. public static void main(String[] args) throws Exception {
  3. List<Map<String,Object>> list=new ArrayList(){{
  4. add(new HashMap(){{put("a",1);put("c",3);}});
  5. add(new HashMap(){{put("a",11);put("b",2);}});
  6. add(new HashMap(){{put("a",111);put("c",3);}});
  7. add(new HashMap(){{put("b",22);}});
  8. add(new HashMap(){{put("a",1111);put("b",222);}});
  9. }};
  10. System.out.println(sortListMapValueDesc(list));
  11. }
  12. /**
  13. * 先分组后排序
  14. * @param org 原始map的List
  15. * @return
  16. */
  17. public static String sortListMapValueDesc(List<Map<String,Object>> org){
  18. //5.定义List<String> key,保存key用于分组及排序
  19. List<String> keystore=new ArrayList<>();
  20. //3.定义分组容器Map<List<Map>>
  21. Map<String,List<Map<String,Object>>> groupMap= new HashMap<String,List<Map<String,Object>>>();
  22. //1.遍历原始list进行分组
  23. org.forEach(ls->{
  24. //2.嵌套遍历map进行分组
  25. Set<String> keySet=ls.keySet();
  26. keySet.forEach(k->{
  27. //存储分组的key(看结果暂时没用到,groupMap的key自动排序了好尴尬)
  28. if(!keystore.contains(k)){
  29. keystore.add(k);
  30. }
  31. //定义key相同的同组Map
  32. Map<String,Object> groupedMap=new HashMap<String,Object>();
  33. groupedMap.put(k,ls.get(k));
  34. //判断是否已有分组初始化分组的List
  35. if(!groupMap.containsKey(k)){
  36. //4.定义分组的List<Map>
  37. List<Map<String,Object>> groupList=new ArrayList<Map<String,Object>>();
  38. groupList.add(groupedMap);
  39. groupMap.put(k,groupList);
  40. }else {
  41. //获取已经创建的List并add
  42. groupMap.get(k).add(groupedMap);
  43. }
  44. });
  45. });
  46. //6.将分组的结果groupMap排序:(List<Map>的MapValue降序)
  47. groupMap.keySet().forEach(gks->groupMap.get(gks).sort(new Comparator<Map<String, Object>>() {
  48. @Override
  49. public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  50. return o2.get(gks).toString().compareTo(o1.get(gks).toString());
  51. }
  52. }));
  53. //todo 7对Map的key进行排序(暂时没有必要)
  54. return groupMap.toString();
  55. }
  56. }

欢迎交流


0
0
0

添加评论

正在回复:
取消
0
0
0
0