java常用代码块
为了减少手写出现的错误,可以直接复制使用,大部分是经常使用的代码,对map操作,list 分组,排序,后续可以放到IDEA做成快捷键
map 根据Key排序 1 2 3 4 5 6 7 private static Map<String, Object> sortByKey (Map<String, Object> map) { Map<String, Object> result = new LinkedHashMap<>(map.size()); map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
map 进行遍历 1 2 3 4 for (Map.Entry<String, Object> m : map.entrySet()) { System.out.println("key:" + m.getKey() + " value:" + m.getValue()); }
list 对象根据某个字段分组 1 2 3 4 5 6 7 Map<Object,List<Object>> map = demoList.stream().collect(Collectors.groupingBy(Object::getAttr)); Map<String, List<Object>> groupBy = objectList.stream().collect(Collectors .groupingBy(o -> o.getAttr1() + "_" + o.getAttr2())); Set<Long> attrs = list.stream().map(Object::getAttr).collect(Collectors.toSet());
list 用stream进行排序 . 1 2 3 4 5 6 List<String> stortList = list.stream().sorted().collect(Collectors.toList()); List<Object> sortList = objectList.stream().sorted(Comparator.comparing(Object::getAttr) .reversed()).collect(Collectors.toList());
list 用Guava进行拆分分页 1 List<List<Long>> splitList = Lists.partition(list, 200 );
jodaTime 两个日期相差小时,天 ,分钟 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 DateTime dt1 = new DateTime("2020-09-05" ); dt1 = dt1.plusDays(1 ).plusMinutes(1 ).plusHours(1 ); DateTime dt2 = new DateTime("2020-09-06" ); System.out.println(dt1); System.out.println(dt2); int hours = Hours.hoursBetween(dt1, dt2).getHours();int days = Days.daysBetween(dt1,dt2).getDays();int minutes = Minutes.minutesBetween(dt1,dt2).getMinutes();System.out.println(hours+" " +days+" " +minutes); DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss" ); DateTime dateTimeStart = dateTimeFormatter.parseDateTime("2022-09-12 00:00:00" );
两个时间是否有交集 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Date startTime1 = new DateTime("2021-01-10" ).toDate(); Date endTime1 = new DateTime("2021-02-16" ).toDate(); Date startTime2 = new DateTime("2021-01-09" ).toDate(); Date endTime2 = new DateTime("2021-01-24" ).toDate(); if ((startTime1.getTime() > startTime2.getTime() && startTime1.getTime() < endTime2.getTime()) || (endTime1.getTime() > startTime2.getTime() && endTime1.getTime() < endTime2.getTime()) || (startTime2.getTime() > startTime1.getTime() && endTime2.getTime() < endTime1.getTime()) ) { System.out.println("有交集" ); } if (((startTime1.getTime() >= startTime2.getTime()) || (endTime1.getTime() <= startTime2.getTime())) && ((startTime1.getTime() <= startTime2.getTime()) || (startTime1.getTime() >= endTime2.getTime()))) { System.out.println("无交集" ); }