1、先来体验一下lambda最直观的优点:简洁代码
@Test
public void lambaTest(){
Comparator<Integer> cpt2 = (x,y) -> Integer.compare(x, y);
TreeSet<Integer> ts = new TreeSet<Integer>(cpt2);
ts.add(4);
ts.add(3);
ts.add(1);
ts.add(5);
ts.add(0);
ts.forEach(l -> {
System.out.println("==========="+l);
});
}
2、定义下过滤方法
@Test
public void lambaTest2(){
List<Product> proList = new ArrayList<Product>();
Product p1 = new Product();
p1.setPrice(100);
p1.setName("张三");
proList.add(p1);
Product p2 = new Product();
p2.setPrice(200);
p2.setName("李四");
proList.add(p2);
List<Product> products = filterMapByCondition(proList, (p) -> p.getPrice() > 100);
for (Product pro : products){
System.out.println(pro);
}
}
class Product{
private int price;
private String name;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public interface MyPredicate <T> {
boolean test(T t);
}
private List<Product> filterMapByCondition(List<Product> proList,MyPredicate<Product> mp){
List<Product> prods = new ArrayList<>();
for (Product prod : proList){
if (mp.test(prod)){
prods.add(prod);
}
}
return prods;
}
3、使用流stream API过滤筛选
@Test
public void streamTest(){
List<Integer> ll = new ArrayList<Integer>();
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
ll.add(5);
ll.add(6);
ll.forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
ll.stream().filter(l -> l > 1).limit(4).forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
ll.stream().filter(l -> l > 1).map(l -> l+2).forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
List<Integer> l2 = ll.stream().filter(l -> l > 4).collect(Collectors.toList());
l2.forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
System.out.print(l2.stream().mapToInt(Integer::valueOf).sum());
}
二、函数式接口
@Test
public void funTest(){
System.out.println(changeNum(4L,(x) -> x - 1));
Function<String,String> fun = (x) -> x+ "1";
System.out.println(fun.apply("a"));
}
/**
* Function<T,R> 函数式接口
* @param num
* @param fun
* @return
*/
public Long changeNum(Long num, Function<Long, Long> fun){
return fun.apply(num);
}
三、供给型接口
@Test
public void test2(){
String value = getValue(() -> "hello");
System.out.println(value);
}
/**
* Supplier<T> 供给型接口
* @param sup
* @return
*/
public String getValue(Supplier<String> sup){
return sup.get();
}
四、消费型接口
@Test
public void test(){
changeStr("hello",(str) -> System.out.println(str));
}
/**
* Consumer<T> 消费型接口
* @param str
* @param con
*/
public void changeStr(String str, Consumer<String> con){
con.accept(str);
}
五、Stream API
求和、最大值、最小值、过滤等
package com.zhouzy.classlodertest;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamDemo {
static class User{
User(Integer id,String name ,Integer age,String address){
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
User(){
}
private Integer id;
private String name;
private Integer age;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public static void main(String[] args) {
User user1 = new User(1,"jim",23,"北京");
User user2 = new User(2,"tom",24,"武汉");
User user3 = new User(3,"echo",25,"深圳");
User user4 = new User(4,"jerry",26,"上海");
User user5 = new User(5,"bob",27,"北京");
/**
* 查找和匹配
* allMatch-检查是否匹配所有元素
* anyMatch-检查是否至少匹配一个元素
* noneMatch-检查是否没有匹配所有元素
* findFirst-返回第一个元素
* findAny-返回当前流中的任意元素
* count-返回流中元素的总个数
* max-返回流中最大值
* min-返回流中最小值
*/
//数据库、集合 : 存数据的
// Stream:计算和处理数据交给 Stream
List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
/* users.stream()
.filter(u->{return u.getId()%2 == 0;})
.filter(u->{return u.getAge() > 24;})
.map(u->{return u.getName().toUpperCase();})
.sorted((u1,u2)->{return u2.compareTo(u1);})
.limit(1)
.forEach(System.out::println);*/
/* IntSummaryStatistics is = users.stream()
.mapToInt(u->{return u.getAge();})
.summaryStatistics();
System.out.println(is.getSum());*/
List<String> infos = users.stream().map(u -> u.getName()).collect(Collectors.toList());
Optional<String> reduced = infos.stream()
.sorted()
.reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
//取年龄最大和最小的
Optional<User> max = users.stream().max((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()));
Optional<User> min = users.stream().min((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()));
System.out.println("最大值:"+max.get().getAge()+",最小值:"+min.get().getAge());
}
}
六、新的日期API LocalDate | LocalTime | LocalDateTime
@Test
public void test(){
// 从默认时区的系统时钟获取当前的日期时间。不用考虑时区差
LocalDateTime date = LocalDateTime.now();
//2018-07-15T14:22:39.759
System.out.println(date);
System.out.println(date.getYear());
System.out.println(date.getMonthValue());
System.out.println(date.getDayOfMonth());
System.out.println(date.getHour());
System.out.println(date.getMinute());
System.out.println(date.getSecond());
System.out.println(date.getNano());
// 手动创建一个LocalDateTime实例
LocalDateTime date2 = LocalDateTime.of(2017, 12, 17, 9, 31, 31, 31);
System.out.println(date2);
// 进行加操作,得到新的日期实例
LocalDateTime date3 = date2.plusDays(12);
System.out.println(date3);
// 进行减操作,得到新的日期实例
LocalDateTime date4 = date3.minusYears(2);
System.out.println(date4);
}
@Test
public void test2(){
// 时间戳 1970年1月1日00:00:00 到某一个时间点的毫秒值
// 默认获取UTC时区
Instant ins = Instant.now();
System.out.println(ins);
System.out.println(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
System.out.println(System.currentTimeMillis());
System.out.println(Instant.now().toEpochMilli());
System.out.println(Instant.now().atOffset(ZoneOffset.ofHours(8)).toInstant().toEpochMilli());
}
@Test
public void test3(){
// Duration:计算两个时间之间的间隔
// Period:计算两个日期之间的间隔
Instant ins1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
Duration dura = Duration.between(ins1, ins2);
System.out.println(dura);
System.out.println(dura.toMillis());
System.out.println("======================");
LocalTime localTime = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime localTime2 = LocalTime.now();
Duration du2 = Duration.between(localTime, localTime2);
System.out.println(du2);
System.out.println(du2.toMillis());
}
@Test
public void test4(){
LocalDate localDate =LocalDate.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalDate localDate2 = LocalDate.of(2016,12,12);
Period pe = Period.between(localDate, localDate2);
System.out.println(pe);
}
@Test
public void test5(){
// temperalAdjust 时间校验器
// 例如获取下周日 下一个工作日
LocalDateTime ldt1 = LocalDateTime.now();
System.out.println(ldt1);
// 获取一年中的第一天
LocalDateTime ldt2 = ldt1.withDayOfYear(1);
System.out.println(ldt2);
// 获取一个月中的第一天
LocalDateTime ldt3 = ldt1.withDayOfMonth(1);
System.out.println(ldt3);
LocalDateTime ldt4 = ldt1.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
System.out.println(ldt4);
// 获取下一个工作日
LocalDateTime ldt5 = ldt1.with((t) -> {
LocalDateTime ldt6 = (LocalDateTime)t;
DayOfWeek dayOfWeek = ldt6.getDayOfWeek();
if (DayOfWeek.FRIDAY.equals(dayOfWeek)){
return ldt6.plusDays(3);
}
else if (DayOfWeek.SATURDAY.equals(dayOfWeek)){
return ldt6.plusDays(2);
}
else {
return ldt6.plusDays(1);
}
});
System.out.println(ldt5);
}
@Test
public void test6(){
// DateTimeFormatter: 格式化时间/日期
// 自定义格式
LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String strDate1 = ldt.format(formatter);
String strDate = formatter.format(ldt);
System.out.println(strDate);
System.out.println(strDate1);
// 使用api提供的格式
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
LocalDateTime ldt2 = LocalDateTime.now();
String strDate3 = dtf.format(ldt2);
System.out.println(strDate3);
// 解析字符串to时间
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt4 = LocalDateTime.parse("2017-09-28 17:07:05",df);
System.out.println("LocalDateTime转成String类型的时间:"+localTime);
System.out.println("String类型的时间转成LocalDateTime:"+ldt4);
}
// ZoneTime ZoneDate ZoneDateTime
@Test
public void test7(){
LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now);
LocalDateTime now2 = LocalDateTime.now();
ZonedDateTime zdt = now2.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zdt);
Set<String> set = ZoneId.getAvailableZoneIds();
set.stream().forEach(System.out::println);
}
* 之前使用的java.util.Date月份从0开始,我们一般会+1使用,很不方便,java.time.LocalDate月份和星期都改成了enum
* java.util.Date和SimpleDateFormat都不是线程安全的,而LocalDate和LocalTime和最基本的String一样,是不变类型,不但线程安全,而且不能修改。
* java.util.Date是一个“万能接口”,它包含日期、时间,还有毫秒数,更加明确需求取舍
* 新接口更好用的原因是考虑到了日期时间的操作,经常发生往前推或往后推几天的情况。用java.util.Date配合Calendar要写好多代码,而且一般的开发人员还不一定能写对。
1、LocalDate
public static void localDateTest() {
//获取当前日期,只含年月日 固定格式 yyyy-MM-dd 2018-05-04
LocalDate today = LocalDate.now();
// 根据年月日取日期,5月就是5,
LocalDate oldDate = LocalDate.of(2018, 5, 1);
// 根据字符串取:默认格式yyyy-MM-dd,02不能写成2
LocalDate yesteday = LocalDate.parse("2018-05-03");
// 如果不是闰年 传入29号也会报错
LocalDate.parse("2018-02-29");
}
2、LocalDate常用转化
/**
* 日期转换常用,第一天或者最后一天...
*/
public static void localDateTransferTest(){
//2018-05-04
LocalDate today = LocalDate.now();
// 取本月第1天: 2018-05-01
LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth());
// 取本月第2天:2018-05-02
LocalDate secondDayOfThisMonth = today.withDayOfMonth(2);
// 取本月最后一天,再也不用计算是28,29,30还是31: 2018-05-31
LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
// 取下一天:2018-06-01
LocalDate firstDayOf2015 = lastDayOfThisMonth.plusDays(1);
// 取2018年10月第一个周三 so easy?: 2018-10-03
LocalDate thirdMondayOf2018 = LocalDate.parse("2018-10-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.WEDNESDAY));
}
3、LocalTime
public static void localTimeTest(){
//16:25:46.448(纳秒值)
LocalTime todayTimeWithMillisTime = LocalTime.now();
//16:28:48 不带纳秒值
LocalTime todayTimeWithNoMillisTime = LocalTime.now().withNano(0);
LocalTime time1 = LocalTime.parse("23:59:59");
}
4、LocalDateTime
public static void localDateTimeTest(){
//转化为时间戳 毫秒值
long time1 = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
long time2 = System.currentTimeMillis();
//时间戳转化为localdatetime
DateTimeFormatter df= DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println(df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time1),ZoneId.of("Asia/Shanghai"))));
}