- 行为参数化:你可以将代码块作为参数传递给另一个方法,稍后再去执行它,这样这个方法的行为就基于那块代码被参数化了
- lambda表达式:可以作为参数传递给方法或存储在变量中
-
package map; import java.util.Arrays; import java.util.List; /** * @author: chenger * @description: * @date: 2021/3/5 上午11:30 **/ public class Test { public int value = 2; public static void main(String[] args) { new Test().cal(); } public void cal() { final int value = 3; Runnable runnable1 = new Runnable() { public int value = 4; @Override public void run() { System.out.println(Test.this.value); System.out.println(this.value); // 匿名内部类里的value 覆盖了 方法里的value 导致方法里的value永远读不出来 System.out.println(value); } }; // lambda表达式 传递给变量 -> 匿名内部类的缩写 Runnable runnable2 = () -> System.out.println(value); runnable1.run(); runnable2.run(); /** * lambda表达式 传递给方法 * 如果要升序排序:a1-a2 * 如果要降序排序:a2-a1 */ List<Integer> i = Arrays.asList(1, 4, 2, 19, 22, 54, 3, 199); i.sort((a1, a2) -> a1 > a2 ? 1 : -1); Thread thread = new Thread(() -> System.out.println(this.value)); thread.start(); } }
-
- 表达式和语句的区别
- Stream常用操作
- 中间操作(可以连接起来的流操作)
-
/** * 尽管filter 和 map是两个独立的操作,但它们合并到同一次遍历中了(循环合并) */ List<String> lists = Arrays.asList("aaaaaa", "bbb", "cccc", "dddddd"); lists.stream().filter(s -> { System.out.println("filter " + s); return s.length() > 5; }).map(s -> { System.out.println("map " + s); return s; }).collect(Collectors.toList()); 输出: filter aaaaaa map aaaaaa filter bbb filter cccc filter dddddd map dddddd
- filter
- map
- limit
- skip
- sorted
- distinct
- flatmap
-
- 终端操作(关闭流)
- forEach
- collect
- count
- anyMatch 流中是否有一个元素能匹配 T -> boolean
- noneMatch 是否没有元素能匹配
- allMatch 是否所有元素都能匹配
- findAny () -> Optional<T> 如果你不关心返回的元素是哪个,请使用findAny
- findFirst
- reduce 接受两个参数 1.一个初始值 2.BinaryOperator<T> 的抽象方法 R apply(T t, U u) 接受两个参数 返回一个参数
- (T t, BinaryOperator<T> b)
- int sum = numbers.stream().reduce(0, (a, b) -> a+b); 元素求和 numbers.stream().reduce(0, Integer::sum); 变体: Optional<Integer> sum = numbers.stream().reduce(Integer::sum);为什么用Optional?考虑到流中没有任何元素的情况
- int product = numbers.stream().reduce(1, (a, b) -> a*b); 元素乘积
- int maxValue = numbers.stream().reduce(Integer.MIN_VALUE, Integer::max); 最大值
- int minValue = numbers.stream().reduce(Integer.MAX_VALUE, Integer::min); 最小值
- Arrays.stream(String[]) 变成 Stream<String>
- 原始类型流:避免不必要的装箱操作
- 数值流 IntStream DoubleStream LongStream
- xxx.stream().mapToInt(xxxx::getxxx).sum(); 这样更便于计算总数 类似还有max() min() average()(平均值)
- IntStream、LongStream 的range(1,100) rangeClosed(1, 100) (包括一百)
- 数值流 IntStream DoubleStream LongStream
- boxed()方法 把原始流转换成一般流 xxxStream(T) -> Stream<T>
- 构建流
- Stream.of(xxx, xxx, xxx); 从数值创建流
- Stream.empty(); 得到一个空流
- Arrays.stream(xxx[]) 从数组创建流
- Stream<String> lines = Files.lines(Paths.get("xxx.txt"), Charset.defaultCharset()) 从文件创建流
- 创建无限流
- Stream.iterate(0, n->n+2) 每次计算+2 0 2 4 6 8 10 。。。。 T -> R
-
/** * 使用无限流生成斐波那契数列 0 1 1 2 3 5 8.... * 生成前20个 */ Stream.iterate(new int[]{0, 1}, n -> new int[]{n[1], n[0] + n[1]}).limit(20).map(n -> n[0]).forEach(System.out::println);
-
- Strea.generate(Math::random) () -> T
- Stream.iterate(0, n->n+2) 每次计算+2 0 2 4 6 8 10 。。。。 T -> R
- 用流收集数据
- 收集常用信息的收集器 IntSummaryStatistics 包括getCount() getSum() getMin() getMax() getAverage()
- IntSummaryStatistics summaries = menu.stream().collect(summarizingInt(Dish::getCalories));
- Collectors类
- joining() 会调用流中没一个对象的toString()方法把所有字符串拼接成一个字符串 可以接受分隔符 joining(",")
- reducing()
- groupingBy()
- partitioningBy() T -> boolean
- 收集常用信息的收集器 IntSummaryStatistics 包括getCount() getSum() getMin() getMax() getAverage()
- 调用静态方法省略类名的技巧 import static java.util.stream.Collectors.*; 这样就可以使用时省略类名Collectors xxxxx.collect(toList())
- 设计模式使用函数式接口-Lambda表达式实现
- 策略模式
- 模板模式
- 观察者模式
- 责任链模式
- 工厂模式
- 默认方法
- 如果一个类使用相同的方法签名从多个地方(比如另一个类或接口)继承了方法 时的 解决冲突
- 类中的方法优先级最高。类或父类中声明的方法的优先级高于任何声明为默认方法的优先级
- 如果无法依据第一条进行判断,那么子接口的优先级更高:函数签名相同时,优先选择拥有最具体实现的默认方法的接口,即如果B继承了A那么B就比A更加具体。
- 最后,如果还是无法判断,集成了多个接口的类必须通过显示覆盖和调用期望的方法,显示地选择使用哪一个默认方法的实现
- 如果一个类使用相同的方法签名从多个地方(比如另一个类或接口)继承了方法 时的 解决冲突
- CompletableFuture组合式异步编程
- 新的日期和时间API
-
package date.time; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.*; import java.util.Locale; /** * @author: chenger * @description: java8 新增日期和时间API * @date: 2021/3/17 上午9:44 **/ public class Java8Test { public static void main(String[] args) { localDateTest(); localTimeTest(); localDateTimeTest(); instantTest(); durationTest(); periodTest(); temporalAdjusterTest(); dateTimeFormatterTest(); zoneIdTest(); } /** * LocalDate测试方法 * 年月日 */ public static void localDateTest() { System.out.println("--------------LocalDate------------------"); // LocalDate localDate = LocalDate.of(2021, 3, 15); LocalDate localDate = LocalDate.now(); System.out.println(localDate.getYear()); System.out.println(localDate.getMonth() + " " + localDate.getMonthValue()); System.out.println(localDate.getDayOfMonth()); System.out.println("周几:" + localDate.getDayOfWeek()); System.out.println("今年第几天:" + localDate.getDayOfYear()); System.out.println(localDate.lengthOfMonth()); System.out.println("是否为闰年:" + localDate.isLeapYear()); // 使用TemporalFeild读取LocalDate的值 (这里会涉及到一个ChronoFeild枚举->实现了TemporalFeild接口) System.out.println("使用get方法获取:" + localDate.get(ChronoField.YEAR)); System.out.println("使用get方法获取:" + localDate.get(ChronoField.MONTH_OF_YEAR)); System.out.println("使用get方法获取:" + localDate.get(ChronoField.DAY_OF_MONTH)); // 查询 没有的枚举 会抛出异常 java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay // System.out.println("使用get方法获取:" + localDate.get(ChronoField.HOUR_OF_DAY)); // 解析字符串 创建LocalDate LocalDate parse = LocalDate.parse("2021-02-28"); System.out.println(parse.getYear()); System.out.println(parse.getMonth() + " " + localDate.getMonthValue()); System.out.println(parse.getDayOfMonth()); System.out.println(localDate); // with直接替换原来的值 并生成一个 新的对象 // 月份 被替换成 12月 System.out.println(localDate.with(ChronoField.MONTH_OF_YEAR, 12)); // plus 累增 System.out.println(localDate.plus(6, ChronoUnit.DAYS)); System.out.println(localDate.plusWeeks(2)); // minus 相减 System.out.println(localDate.minus(1, ChronoUnit.YEARS)); System.out.println(localDate.minusDays(10)); } /** * LocalTest测试方法 * 时分秒 */ public static void localTimeTest() { System.out.println("-------------------LocalTime----------------------"); // LocalTime localTime = LocalTime.of(10, 35, 42); LocalTime localTime = LocalTime.parse("11:53:55"); // LocalTime.now(); System.out.println(localTime.getHour()); System.out.println(localTime.getMinute()); System.out.println(localTime.getSecond()); System.out.println(localTime.getNano()); System.out.println(localTime); } /** * LocalDateTime测试方法 * 年月日时分秒 */ public static void localDateTimeTest() { System.out.println("---------------LocalDateTime-----------------------"); // LocalDateTime.now(); LocalDate localDate = LocalDate.parse("2021-02-28"); LocalTime localTime = LocalTime.parse("11:53:55"); LocalDateTime localDateTime1 = LocalDateTime.of(2021, 4, 6, 12, 59, 35); LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime); LocalDateTime localDateTime3 = localDate.atTime(22, 43, 32); LocalDateTime localDateTime4 = localDate.atTime(localTime); LocalDateTime localDateTime5 = localTime.atDate(localDate); System.out.println(localDateTime1); // 从LocalDateTime提取LocalDate、LocalTime LocalDate localDate1 = localDateTime1.toLocalDate(); LocalTime localTime1 = localDateTime1.toLocalTime(); } /** * Instant测试方法 * Instant的设计初衷是为了便于机器使用 用于获取某个时刻的时间戳 */ public static void instantTest() { System.out.println("----------------Instant------------------"); Instant instant1 = Instant.now(); // ofEpochSecond 时间是从 1970-01-01 00:00:00开始计算 Instant instant2 = Instant.ofEpochSecond(4); // 五秒之前的100万纳秒(1秒) Instant instant3 = Instant.ofEpochSecond(5, -1_000_000_000); // 三秒之后的100万纳秒(1秒) Instant instant4 = Instant.ofEpochSecond(3, 1_000_000_000); System.out.println(instant1); System.out.println(instant2); System.out.println(instant3); System.out.println(instant4); } /** * Duration测试方法 * 主要用于LocalTime、LocalDateTime、Instant两个值之间的时间差 * 主要用秒和纳秒衡量时间的长短 */ public static void durationTest() { System.out.println("---------------Duration-----------------------"); LocalDateTime localDateTime1 = LocalDateTime.of(2021, 4, 6, 12, 59, 35); LocalDate localDate = LocalDate.parse("2021-02-28"); LocalTime localTime = LocalTime.parse("11:53:55"); LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime); System.out.println(Duration.between(localDateTime1, localDateTime2)); System.out.println(Duration.between(localDateTime2, localDateTime1)); System.out.println(Duration.ofMinutes(3)); System.out.println(Duration.of(3, ChronoUnit.DAYS)); } /** * Period测试方法 * 主要用于LocalDate两个值之间的时间差 * 以年、月、日的方式衡量时间的长短 */ public static void periodTest() { System.out.println("---------------Period-----------------------"); LocalDate localDate1 = LocalDate.of(2020, 1, 15); LocalDate localDate2 = LocalDate.now(); System.out.println(Period.between(localDate1, localDate2)); System.out.println(Period.between(localDate2, localDate1)); System.out.println(Period.ofWeeks(5)); System.out.println(Period.ofDays(55)); System.out.println(Period.of(1, 2, 3)); } /** * TemporalAdjuster测试方法 * 用于对日期进行更加复杂的操作 */ public static void temporalAdjusterTest() { System.out.println("---------------TemporalAdjusters-----------------------"); LocalDate localDate = LocalDate.of(2021, 3, 19); System.out.println(localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))); System.out.println(localDate.with(TemporalAdjusters.lastDayOfMonth())); // 查询下一个工作日是周几 System.out.println(cal(localDate, (Temporal temporal) -> { DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); int dayToAdd = 1; if(dayOfWeek == DayOfWeek.FRIDAY) { dayToAdd = 3; } else if(dayOfWeek == DayOfWeek.SATURDAY) { dayToAdd = 2; } return temporal.plus(dayToAdd, ChronoUnit.DAYS); })); } public static Temporal cal(Temporal temporal, TemporalAdjuster temporalAdjuster) { return temporalAdjuster.adjustInto(temporal); } /** * DateTimeFormatter测试方法 * 格式化日期 */ public static void dateTimeFormatterTest() { System.out.println("---------------DateTimeFormatter-----------------------"); LocalDate localDate = LocalDate.of(2021, 3, 19); System.out.println(localDate.format(DateTimeFormatter.BASIC_ISO_DATE)); System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE)); // 按照某个特定模式创建格式器 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); System.out.println(localDate.format(dateTimeFormatter)); // 上面ofPattern方法的重载版本,可以多接收一个Locale(区域设置)参数 DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.CHINESE); System.out.println(localDate.format(timeFormatter)); } /** * ZoneId测试方法 * 处理时区 */ public static void zoneIdTest() { System.out.println("---------------ZoneId-----------------------"); ZoneId zoneId = ZoneId.of("Europe/Rome"); LocalDate localDate = LocalDate.of(2021, 3, 19); System.out.println(localDate.atStartOfDay(zoneId)); LocalDateTime localDateTime = LocalDateTime.of(2021, 4, 6, 12, 59, 35); System.out.println(localDateTime.atZone(zoneId)); Instant instant = Instant.now(); System.out.println(instant.atZone(zoneId)); // Instant instant1 = localDateTime.toInstant(zoneId); LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, zoneId); ZoneOffset zoneOffset = ZoneOffset.of("-05:00"); OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime, zoneOffset); System.out.println(offsetDateTime); } }
-
- foreach 和 stream().foreach https://baijiahao.baidu.com/s?id=1637952388544934539&wfr=spider&for=pc
- 超越java8
- HashMap 方法
- Integer count = map.getOrDefault("Chenger", 0); 如果没找到指定键,就返回 0
- map.computeIfAbsent(url. this::getData); 如果url为键的 value 不存在 把getData(url)结果传进去
- HashMap 方法
- 中间操作(可以连接起来的流操作)
java8实战-笔记
最新推荐文章于 2022-05-15 22:08:18 发布