jdk1.8新特性学习
package com.xll.code.jdk1_8study; import com.xll.code.jdk1_8study.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.convert.converter.Converter; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.*; @SpringBootTest class Jdk18StudyApplicationTests { @Test public void contextLoads() { Runnable runnable=new Runnable() { @Override public void run() { System.out.println("runnable:hello"); } }; new Thread(runnable).start(); //等效于上面 Runnable runnable01= () -> System.out.println("runnable01:hello"); new Thread(runnable01).start(); TreeSet<String> treeSet01=new TreeSet<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return Integer.compare(o1.length(),o2.length()); } }); treeSet01.add("aa"); treeSet01.add("aaa"); treeSet01.add("a"); System.out.println("treeSet01:"+treeSet01); TreeSet<String> treeSet02=new TreeSet<>((o1, o2) -> Integer.compare(o1.length(),o2.length())); treeSet02.add("aa"); treeSet02.add("a"); treeSet02.add("aaa"); System.out.println("treeSet02:"+treeSet01); TreeSet<String> treeSet03=new TreeSet<>(Comparator.comparingInt(String::length)); treeSet03.add("aaa"); treeSet03.add("a"); treeSet03.add("aa"); System.out.println("treeSet03:"+treeSet01); } @Test public void testConsumer(){ //一个参数,小括号可省略 Consumer<String> conn= x-> System.out.println(x); conn.accept("hello"); /**2.andThen链式*/ Consumer<Integer> consumer1 = x -> System.out.println("first x : " + x); Consumer<Integer> consumer2 = x -> { System.out.println("second x : " + x); // throw new NullPointerException("throw exception test"); }; Consumer<Integer> consumer3 = x -> System.out.println("third x : " + x); consumer1.andThen(consumer2).andThen(consumer3).accept(1); //作用:1.处理对象中的某个字段值 Consumer<User> userConsumer = x ->{ x.setId(1L); x.setUsername("xll"); }; User user = new User(); user.setPassword("123456"); userConsumer.accept(user); System.out.println(user.toString()); DoubleConsumer doubleConsumer = x ->{ System.out.println("doubleConsumer:"+(x+1)); }; DoubleConsumer doubleConsumer01 = x ->{ System.out.println("doubleConsumer:"+(x)); }; DoubleConsumer doubleConsumer02 = x ->{ System.out.println("doubleConsumer:"+(x+1)); }; doubleConsumer.andThen(doubleConsumer01).andThen(doubleConsumer02).accept(1001); LongConsumer longConsumer = x ->{ System.out.println("longConsumer:"+(x+1)); }; LongConsumer longConsumer01 = x ->{ System.out.println("longConsumer:"+(x)); }; LongConsumer longConsumer02 = x ->{ System.out.println("longConsumer:"+(x+1)); }; longConsumer.andThen(longConsumer01).andThen(longConsumer02).accept(1001L); ObjIntConsumer<User> objIntConsumer = (x, y) ->{ System.out.println("第"+y+",user:"+x); }; User user1 = new User(); user1.setId(1L); objIntConsumer.accept(user1, 1); ObjIntConsumer<User> objIntConsumer01 = (x,y) ->{ System.out.println("第"+y+",user:"+x); }; User user2 = new User(); user1.setId(2L); objIntConsumer01.accept(user2, 2); ObjIntConsumer<User> objIntConsumer02 = (x,y) ->{ System.out.println("第"+y+",user:"+x); }; User user3 = new User(); user1.setId(3L); objIntConsumer02.accept(user3, 3); } @Test public void testConverter(){ Converter<String, Integer> converter = Integer::valueOf; Integer converted = converter.convert("123"); System.out.println(converted+1); // 123 } @Test public void testPredicate(){ Predicate<String> predicate = (s) -> s.length() > 0; predicate.test("foo"); // true predicate.negate().test("foo"); // false Predicate<Boolean> nonNull = Objects::nonNull; Predicate<Boolean> isNull = Objects::isNull; Predicate<String> isEmpty = String::isEmpty; Predicate<String> isNotEmpty = isEmpty.negate(); } @Test public void testFunction(){ Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123" System.out.println(backToString.apply("123")); } @Test public void testSupplier(){ Supplier<User> personSupplier = User::new; personSupplier.get().setUsername("xll"); // new Person System.out.println(personSupplier.get()); } @Test public void testComparator (){ Comparator<User> comparator = (p1, p2) -> p1.getUsername().compareTo(p2.getUsername()); User p1 = new User(1L,"John", "Doe"); User p2 = new User(2L,"Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 System.out.println(comparator.compare(p1, p2)); comparator.reversed().compare(p1, p2); // < 0 System.out.println(comparator.reversed().compare(p1, p2)); } @Test public void testOptional (){ Optional<String> optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" } /** * 重点:流 */ @Test public void testStream (){ List<String> stringCollection = new ArrayList<>(); stringCollection.add("ddd2"); stringCollection.add("aaa2"); stringCollection.add("bbb1"); stringCollection.add("aaa1"); stringCollection.add("bbb3"); stringCollection.add("ccc"); stringCollection.add("bbb2"); stringCollection.add("ddd1"); //1.Filter 过滤 stringCollection.stream().filter((s) -> s.startsWith("a")).forEach(System.out::println); System.out.println("----------------------------------"); //2.Sort 排序 stringCollection.stream().sorted().filter((s) -> s.startsWith("a")).forEach(System.out::println); System.out.println("----------------------------------"); //3.Map 映射 stringCollection.stream().map(String::toUpperCase).sorted((a, b) -> b.compareTo(a)).forEach(System.out::println); //4.Match 匹配 boolean anyStartsWithA = stringCollection.stream().anyMatch((s) -> s.startsWith("a")); System.out.println(anyStartsWithA); // true boolean allStartsWithA = stringCollection.stream().allMatch((s) -> s.startsWith("a")); System.out.println(allStartsWithA); // false boolean noneStartsWithZ = stringCollection.stream().noneMatch((s) -> s.startsWith("z")); System.out.println(noneStartsWithZ); // true //5.limit 线段流,使其不超过指定数量 stringCollection.stream().sorted().limit(2).forEach(s-> System.out.println(s));//"aaa1","aaa2" //6.skip(n)—— 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit互补 stringCollection.stream().sorted().skip(2).forEach(s-> System.out.println(s)); //7.distinct——筛选,通过流所生成元素的hashCode()和equals去除重复元素 stringCollection.stream().sorted().distinct().forEach(s-> System.out.println(s)); //8.Count 计数,计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。 long startsWithB = stringCollection.stream().filter((s) -> s.startsWith("b")).count(); System.out.println(startsWithB); // 3 //9.Reduce 规约,这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规越后的结果是通过Optional接口表示的 Optional<String> reduced = stringCollection.stream().sorted().reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" //10.并行Streams 前面提到过Stream有串行和并行两种,串行Stream上的操作是在一个线程中依次完成,而并行Stream则是在多个线程上同时执行 int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } //串行流 long t01 = System.nanoTime(); long count01 = values.stream().sorted().count();//串行 System.out.println(count01); long t02 = System.nanoTime(); long millis01 = TimeUnit.NANOSECONDS.toMillis(t02 - t01); System.out.println(String.format("sequential sort took: %d ms", millis01)); // 串行耗时: 899 ms //并行流 long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count();//并行 System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis)); // 并行排序耗时: 472 ms //11.Map类型不支持stream,不过Map提供了一些新的有用的方法来处理一些日常任务 Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); } map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33 map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33 map.getOrDefault(42, "not found"); // not found //Merge做的事情是如果键名不存在则插入,否则则对原键对应的值做合并操作并重新插入到map中。 map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9 map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat } /** * jdk1.8新日期API学习 */ @Test public void testLocalDate(){ System.out.println("---------------------LocalDate study start--------------------------"); LocalDate date = LocalDate.of(2019, 11, 8); int year = date.getYear(); //2019 System.out.println("year:"+year); Month month = date.getMonth(); System.out.println("month:"+month); int dayOfMonth = date.getDayOfMonth(); System.out.println("dayOfMonth:"+dayOfMonth); DayOfWeek dayOfWeek = date.getDayOfWeek(); System.out.println("dayOfWeek:"+dayOfWeek); int length = date.lengthOfMonth(); System.out.println("length:"+length); boolean leapYear = date.isLeapYear(); System.out.println("leapYear:"+leapYear); LocalDate now = LocalDate.now(); System.out.println("now:"+now); int y = date.get(ChronoField.YEAR); System.out.println("y:"+y); int m = date.get(ChronoField.MONTH_OF_YEAR); System.out.println("m:"+m); int d = date.get(ChronoField.DAY_OF_MONTH); System.out.println("d:"+d); LocalDate date1 = LocalDate.now(); LocalDate date2 = date1.withYear(2018); LocalDate date3 = date2.withDayOfMonth(25); LocalDate date4 = date3.with(ChronoField.MONTH_OF_YEAR, 9); System.out.println("date1:"+date1); System.out.println("date2:"+date2); System.out.println("date3:"+date3); System.out.println("date4:"+date4); LocalDate date01 = LocalDate.now(); LocalDate date02 = date1.plusWeeks(1); LocalDate date03 = date2.minusYears(3); LocalDate date04 = date3.plus(6, ChronoUnit.MONTHS); System.out.println("date01:"+date01); System.out.println("date02:"+date02); System.out.println("date03:"+date03); System.out.println("date04:"+date04); System.out.println("---------------------LocalTime study start--------------------------"); LocalTime time = LocalTime.of(11,59,59); System.out.println("time:"+time); int hour = time.getHour();//3 System.out.println("hour"+hour); int minute = time.getMinute();//10 System.out.println("minute"+minute); int second = time.getSecond();//20 System.out.println("second"+second); System.out.println("---------------------LocalDateTime study start--------------------------"); LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime dt1 = LocalDateTime.of(2019, Month.MARCH, 18, 13, 45, 20); LocalDateTime dt2 = LocalDateTime.of(date, time); System.out.println("dt2:"+dt2); LocalDateTime dt3 = date.atTime(13, 45, 20); System.out.println("dt3:"+dt3); LocalDateTime dt4 = date.atTime(time); System.out.println("dt4:"+dt4); LocalDateTime dt5 = time.atDate(date); System.out.println("dt5:"+dt5); LocalDate localDate1 = dt1.toLocalDate(); System.out.println("localDate1:"+localDate1); LocalTime localTime1 = dt1.toLocalTime(); System.out.println("localTime1:"+localTime1); System.out.println("---------------------Instant study start--------------------------"); //Instant,上面三个有关时间的类都有个一个.toInstant()可转换为Instant()类,可用Date.from(instant)方法转换为Date类 Instant instant1 = Instant.ofEpochSecond(3); System.out.println(instant1);//1970-01-01T00:00:03Z //第一个参数是秒,第二个是纳秒参数,纳秒的存储范围是0至999,999,999 Instant instant2 = Instant.ofEpochSecond(3,0); System.out.println(instant2);//1970-01-01T00:00:03Z //2s之后的在加上100万纳秒(1s) Instant instant3 = Instant.ofEpochSecond(2,1000000000); System.out.println(instant3); //1970-01-01T00:00:03Z Instant instant4 = Instant.ofEpochSecond(4,-1000000000); System.out.println(instant4); //1970-01-01T00:00:03Z System.out.println("---------------------Duration study start--------------------------"); //Duration类的静态工厂方法between就是需要创建两个Temporal对象,计算之间的秒数。LocalDate不能使用。 Duration duration = Duration.between(localTime, localTime1); System.out.println("duration1:"+duration); Duration duration1 = Duration.between(localTime, localTime1); System.out.println("duration1:"+duration1); Duration duration2 = Duration.between(instant1, instant2); System.out.println("duration2:"+duration2); System.out.println("---------------------Period study start--------------------------"); //Period类是以年、月或者日的方式对多个时间单位建模。 LocalDate localDate2 = LocalDate.ofYearDay(11, 9); Period period = Period.between(localDate1,localDate2); System.out.println(period.getYears()); //获取相隔的年份差 0 System.out.println(period.getMonths()); //获取相隔的月份差 11 System.out.println(period.getDays()); //获取相隔的日子差 4 System.out.println("---------------------Period study start--------------------------"); //TemporalAdjuster,有时候需要进行一些更加 //复杂的操作,比如,将日期调整到下个周日、下个工作日,或者是本月的最后一天,这时,可以使用重载Temporal中的with方法,向其传递一个提供了更多定制化选择的TemporalAdjuster对象, //更加灵活地处理日期。 LocalDate date001 = LocalDate.of(2019,11,8);//2019-11-8 LocalDate with = date001.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)); System.out.println("with:"+with); LocalDate with1 = date001.with(TemporalAdjusters.lastDayOfMonth()); System.out.println("with1:"+with1); System.out.println("---------------------DateTimeFormatter study start--------------------------"); //DateTimeFormatter,格式化以及解析日期时间对象 LocalDate date00 = LocalDate.of(2019, 11, 8); String s1 = date00.format(DateTimeFormatter.BASIC_ISO_DATE); System.out.println("s1:"+s1); String s2 = date00.format(DateTimeFormatter.ISO_LOCAL_DATE); System.out.println("s2:"+s2); LocalDate date002 = LocalDate.parse("20191108",DateTimeFormatter.BASIC_ISO_DATE); System.out.println("date002:"+date002); LocalDate date003 = LocalDate.parse("2019-11-08",DateTimeFormatter.ISO_LOCAL_DATE); System.out.println("date003:"+date003); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate date004 = LocalDate.of(2019, 11, 8); System.out.println("date004:"+date004); String formattedDate = date004.format(formatter); System.out.println("formattedDate:"+formattedDate); LocalDate date005 = LocalDate.parse(formattedDate, formatter); System.out.println("date005:"+date005); System.out.println("---------------------ZoneId study start--------------------------"); //ZoneId,是用来处理时区问题的 ZoneId romeZone = ZoneId.of("Europe/Rome"); LocalDate date006 = LocalDate.of(2019, Month.MARCH, 8); ZonedDateTime zonedDateTime = date006.atStartOfDay(romeZone); System.out.println("zonedDateTime:"+zonedDateTime); LocalDateTime dateTime = LocalDateTime.of(2019,Month.MARCH, 8,13,25); ZonedDateTime zonedDateTime1 = dateTime.atZone(romeZone); System.out.println("zonedDateTime1:"+zonedDateTime1); Instant instant = Instant.now(); ZonedDateTime zonedDateTime2 = instant.atZone(romeZone); System.out.println("zonedDateTime2:"+zonedDateTime2); System.out.println("---------------------ZoneOffset study start--------------------------"); //ZoneOffset,利用当前时间和伦敦格林尼治子午线时间的差异: ZoneOffset newYorkOffset = ZoneOffset.of("-05:00"); LocalDateTime dateTime1 = LocalDateTime.of(2019, Month.MARCH, 8, 13, 45); OffsetDateTime dateTimeInNewYork = OffsetDateTime.of(dateTime1, newYorkOffset); System.out.println("dateTimeInNewYork:"+dateTimeInNewYork); } }
美梦成真,变为事实。