jdk8中常用的集合方法和日期方法

Reading time ~41 minutes

此文章为原创文章,引用请标记文章出处: jdk8中常用的集合方法和日期方法

集合List、Set的常用Stream方法

1.List<INSCFeerule>对象集合转换为不重复的INSCFeerule对象属性rulesetid的set集合

List<INSCFeerule> srcRuleList = inscFeeruleDao.selectByFeecontentId(feecontentId);
Set<String> rulesetidList = srcRuleList.stream().map(INSCFeerule::getRulesetid).collect(Collectors.toSet());

2.list集合去重,得到list集合

providerIds=providerIds.stream().distinct().collect(Collectors.toList());

3.判断是否存在符合条件的元素,只要一个符合立刻返回true

boolean isParent=totalInsbListPro.stream().anyMatch((INSBProvider provider)-> StringUtil.isNotEmpty(provider.getParentcode())&& provider.getParentcode().equals(pro.getPrvcode()));

类似还有

noneMatchStream 中没有一个元素符合的才返回 true
list.stream().noneMatch(item->"guizequery".equals(item.getOperator()))

allMatchStream 中全部元素符合传入的 predicate,返回 true

4.将集合inscfees先过滤留下只符合Noti="1"条件的元素,然后映射为自定义的格式String类型数据,最后通过<br>拼接元素返回String类型数据

String temp=inscfees.parallelStream().filter((INSCFeecontent fee)->"1".equals(fee.getNoti())).map((INSCFeecontent fee)->"【"+fee.getDeptname()+" - "+fee.getProvider()+" - "+fee.getVersionno()+"】").collect(Collectors.joining("<br>"));

5.集合元素转为以”,”拼接的String

String newTypeCodeValue=lastTypeCodeList.stream().collect(Collectors.joining(","));

6.List<Map<String,Object>>类型的infoMapList获取key是rulesetid的value的不重复String集合

List<String> addRulesetids=infoMapList.stream().map((Map<String,Object> map)->String.valueOf(map.get("rulesetid"))).distinct().collect(Collectors.toList());

7.List<Map<String,Object>>类型的list获取key是flib_id的value,转为数组类型返回

Arrays.asList(list.stream().map(item -> (String) item.get("flib_id")).toArray();

8.返回特定的结果集合:

List<String> limitLists = forEachLists.stream().skip(2).limit(3).collect(Collectors.toList());

注意skip与limit是有顺序关系的,比如先使用skip(2)会扔掉集合的前两个,然后调用limit(3)会返回前3个

9.按照sortLists里元素的大小进行排序

List<Integer> afterSortLists = sortLists.stream().sorted((In1,In2)->
       In1-In2).collect(Collectors.toList());

10.得到其中长度最大的元素

int maxLength = maxLists.stream().mapToInt(s->s.length()).max().getAsInt();

或者
Optional<Integer> maxLength = maxLists.stream().reduce(Integer::max);

或者
Optional<Object> minObject =objects.stream().min(comparing(Object::getValue));

11.List和Map通过forEach循环过滤得到符合条件的数据

List<Map<String, Object>> queryList = ... ...;
List<Map<String, Object>> policyList = new ArrayList<>();//保存符合条件的数据
 queryList.forEach(map -> {
            map.forEach((k, v) -> {
                if ("policyno".equals(k) && v != null) {
                    policyList.add(map);
                }
            });
        });

12.求和

int sum = numbers.stream().reduce(0, (a, b) -> a + b);

或者
int sum = numbers.stream().reduce(0, Integer::sum);

java8日期常用方法

1.获取当天的日期

System.out.println("---"+LocalDate.now());//---2018-01-17
System.out.println("---"+LocalDateTime.now());//---2018-01-17T14:19:24.525 ,给人阅读的时间戳
System.out.println("---"+Instant.now());//---2018-01-17T06:19:24.525Z,给机器阅读的时间戳

2.获取当前的年月日

LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day); //Year : 2014 Month : 1 day : 14

3.检查两个日期是否相等

LocalDate date1 = LocalDate.of(2014, 01, 14); if(date1.equals(today)){
	//today 2014-01-14 and date1 2014-01-14 are same date
 	System.out.printf("Today %s and date1 %s are same date %n", today, date1);
}

4.获取当前时间,默认的格式是hh:mm:ss:nnn,LocalTime只有时间,没有日期

LocalTime time = LocalTime.now(); System.out.println("local time now : " + time); //local time now : 16:33:33.369

5.判断某个日期是在另一个日期的前面还是后面

LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018, 1, 15);
if(tommorow.isAfter(today)){
     System.out.println("Tomorrow comes after today");
}

6.检查闰年

LocalDate类有一个isLeapYear()的方法能够返回当前LocalDate对应的那年是否是闰年。

7.获取当前时间戳

Instant timestamp = Instant.now();
//What is value of this instant 2018-01-15T10:33:33.379Z
System.out.println("What is value of this instant " + timestamp);

8.使用预定义的格式器来对日期进行解析/格式化,BASICISODATE格式就是yyyy-mm-dd

String str1 = "20180117";
LocalDate formattedstr1 = LocalDate.parse(str1, DateTimeFormatter.BASIC_ISO_DATE);
//Date generated from String 20180117 is 2018-01-17
System.out.printf("Date generated from String %s is %s %n", str1, formattedstr1);

String str2 = "2018-01-17 14:27:30";
LocalDateTime formattedstr2 = LocalDateTime.parse(str2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//Date generated from String 20180117 is 2018-01-17T14:27:30
System.out.printf("Date generated from String %s is %s %n", str1, formattedstr2);

9.使用自定义的格式器来解析日期,可以转为String类型,DateTimeFormatter是不可变且线程安全的

LocalDateTime arrivalDate = LocalDateTime.now();
try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a");
    String landing = arrivalDate.format(format);
    System.out.printf("Arriving at : %s %n", landing);
 } catch (DateTimeException ex) {
    System.out.printf("%s can't be formatted!%n", arrivalDate);
    ex.printStackTrace();
}

jdk-timer、spring-task、quartz的比较

这篇文章将简单介绍目前常用的定时任务框架! Continue reading

小岛经济学-读书笔记

Published on May 10, 2018

java常见的http请求库

Published on May 05, 2018