java8特性:list轉Map並排序
阿新 • • 發佈:2018-12-04
初始程式碼
public Map<String,List<RgwstBean>> getMap(List<RgwstBean> lists){ Map<String,List<RgwstBean>> map = new TreeMap<String,List<RgwstBean>>(); if(lists==null) { return map; } for(RgwstBean rb :lists) { String newdate = rb.getDatetime(); if(map.containsKey(newdate)) { map.get(newdate).add(rb); }else { List<RgwstBean> newlist2 = new ArrayList<RgwstBean>(); newlist2.add(rb); map.put(newdate, newlist2); } } return map; }
lambda語法
public Map<String,List<RgwstBean>> getMap(List<RgwstBean> lists){ //groupingBy無排序 Map<String,List<RgwstBean>> map = lists.stream().collect(Collectors.groupingBy(RgwstBean::getDatetime)); Map<String,List<RgwstBean>> sortmap = new TreeMap<>(); //Map<String,List<RgwstBean>> sortmap = new TreeMap<>((o1,o2)->o2.compareTo(o1));//倒序 map.entrySet() .stream() .forEach(x->sortmap.put(x.getKey(),x.getValue())); return sortmap; }