一些Java常用的代码片段总结,如获取一个时间段内的所有时间,map根据value分组等等
计算一个时间段内的日期集合
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | 
 
 
 
 
 public static List<String> getDateList(LocalDate begin, LocalDate end){
 return Stream.iterate(begin, localDate -> localDate.plusDays(1))
 .limit(ChronoUnit.DAYS.between(begin, end) + 1)
 .map(LocalDate::toString)
 .collect(Collectors.toList());
 }
 
 | 
根据对象的某个字段来升序或降序
| 12
 3
 4
 
 | dictList.sort(Comparator.comparing(Dict::getSort).reversed());
 
 dictList.sort(Comparator.comparing(Dict::getSort));
 
 | 
Map根据value值分组
将Map转换为一个entry集合,然后再用集合分组的方式,就很简单的实现这个功能了
遇到想对Map进行stream处理的时候,就要获取他的entrySet来操作,就是一个List然后里面放着一个一个的Map的entry对象,直接调用e.getKey和e.getValue就能获取每一个map了!
| 1
 | Map<Integer, List<Map.Entry<String,Integer>>>result= SataMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
 | 
对List中的对象进行分组求和(计数)
根据AlarmCountBO里的alarmTypeId进行分组,然后对count字段的值求和,如果想要分组计数,第二个参数就改为Collectors.counting()
| 12
 3
 
 | Map<Integer, Integer> levelCountMap = alarmCount.stream().collect(Collectors.groupingBy(AlarmCountBO::getAlarmTypeId,
 Collectors.summingInt(AlarmCountBO::getCount)));
 
 | 
枚举类转map
| 1
 | Map<Integer, String> stateMap = Arrays.stream(NStateEnum.values()).collect(Collectors.toMap(NStateEnum::getCode, NStateEnum::getDesc));
 | 
实体类转map
使用beanMap,效率高,用了缓存,不费时间,还简单
| 12
 3
 4
 
 | import org.springframework.cglib.beans.BeanMap;BeanMap beanMap = BeanMap.create(screenNumPo);
 
 private static volatile Map<ClassLoader, AbstractClassGenerator.ClassLoaderData> CACHE = new WeakHashMap();
 
 | 
时间戳和日期之间的互相转换
| 12
 3
 4
 
 | import cn.hutool.core.date.DateUtil;import cn.hutool.core.date.DateTime;
 
 DateTime DateUtil.date(Long date)
 
 |