请用Java语言写出对List<Map<String,Object>>进行排序的函数,参数为String[] keys和String[] orders,即涉及排序的key和key对应的升序(ASC)或是降序(DESC).
普通方法实现:
package com.ujiuye.oop; import java.util.*; public class Demo4 { public static void main(String[] args) { Map<String,Integer> map1 = new HashMap<>(); map1.put("AA",100); map1.put("DD",200); Map<String,Integer> map2 = new HashMap<>(); map2.put("ZZ",300); map2.put("BB",400); List<Map<String,Integer>> list = new ArrayList<>(); list.add(map1); list.add(map2); //获取所有的keys Set<String> keys = new HashSet<>(); for (Map<String, Integer> map : list) { keys.addAll(map.keySet()); } //把Set转换成数组 String [] keys2 = keys.toArray(new String [keys.size()] ); Arrays.stream(keys2).forEach(System.out::println); String [] orders={"ASC"};//排序参数 sortList(keys2,orders);//调用方法 System.out.println("排序后的key: "); Arrays.stream(keys2).forEach(System.out::println); //新的List集合 List<Map<String,Integer>> newList = new ArrayList<>(); //根据排序后的key获取Map再放到newList for (int i = 0; i < keys2.length; i++) { String key = keys2[i]; for (Map<String, Integer> map : list) { if (map.containsKey(key)){ Integer value = map.get(key); Map<String,Integer> newMap = new HashMap<>(); newMap.put(key,value); newList.add(newMap); } } } System.out.println("================================"); for (Map<String, Integer> integerMap : newList) { System.out.println(integerMap); } } private static void sortList( String[] keys, String [] orders ){ if (orders[0].equals("ASC")){ //升序 Arrays.sort(keys); }else{ //降序 } } }使用java Stream API实现。
package com.ujiuye.oop; import java.util.*; import java.util.stream.Collectors; public class Demo6 { public static void main(String[] args) { Map<String,Integer> map1 = new HashMap<>(); map1.put("AA",100); map1.put("DD",200); Map<String,Integer> map2 = new HashMap<>(); map2.put("ZZ",300); map2.put("BB",400); List<Map<String,Integer>> list = new ArrayList<>(); list.add(map1); list.add(map2); System.out.println("list.size=====" + list.size()); List<Map.Entry<String, Integer>> collect = list.stream().flatMap(map -> { return map.entrySet().stream(); }).collect(Collectors.toList()); System.out.println(collect); System.out.println("collect.size=====" + collect.size()); List<Map.Entry<String, Integer>> entryList = list.stream().flatMap(map -> { return map.entrySet().stream(); }) .sorted(Comparator.comparing(Map.Entry::getKey)) .collect(Collectors.toList()); System.out.println(entryList); System.out.println("降序......"); List<Map.Entry<String, Integer>> entryList2 = list.stream().flatMap(map -> { return map.entrySet().stream(); }) .sorted(Comparator.comparing(Map.Entry::getKey,Comparator.reverseOrder())) .collect(Collectors.toList()); System.out.println(entryList2); } }