Java8新特性

1. Lambda表达式:允许一个函数作为方法参数传递到方法中去

(parm)->expression;
或
(parm)->{expression;}
  • 实操
Callable<Integer> integerCallable = () -> 5;

IntFunction<Integer> integerIntFunction = (int x) -> (3 * x);

IntBinaryOperator intBinaryOperator = (int a, int b) -> a + b;

Consumer<String> stringConsumer = (String s) -> {
        System.out.println(s);
    };

2. Stream:数据源的元素队列,支持聚合操作(想象成流)

  • 数据源:集合,数组

  • 聚合操作:filter,map,reduce,find,match,sorted

  • 实操

    • filter(过滤)

      List<String> list = new ArrayList();
              list.add("A");
              list.add("");
              list.add("B");
              System.out.println(list);
              List<String> collect = list.stream().filter(x -> !x.isEmpty()).collect(Collectors.toList());
    • forEach(循环)

      list.stream().forEach(x-> System.out.println(x));
    • map(做映射)

       List<Integer> collect1 = list1.stream().map(x -> x * x).collect(Collectors.toList());
    • limit(截取指定数量)

      List<Integer> collect2 = list1.stream().limit(2).collect(Collectors.toList());
    • sorted(排序)

      List<Integer> collect3 = list1.stream().sorted((a, b) -> b.compareTo(a)).collect(Collectors.toList());
    • Collectors(工具类)

      Collectors.toList()
      Collectors.toSet()
      Collectors.toMap()
    • mapToInt(统计操作,max,min,avg,sum)

      IntSummaryStatistics intSummaryStatistics = list1.stream().mapToInt(a -> a).summaryStatistics();
              System.out.println(intSummaryStatistics.getMin());

 3. 接口中提供默认方法和静态方法

  • 默认方法
    public interface DefaultInterfaceDemo {
        
        default void eat(String name){
            System.out.println(name);
        }
    }
  • 静态方法
    static void eat(String name,int count){
            System.out.println(name);
        }

 4. 新的 date api

  • 旧版存在问题:

    • 设计较差(java.util,java.sql 都有date)

    • 非线程安全的

    • 处理时区比较麻烦

  • 新版提供:

    • Local(本地):简化了日期处理,没有时区的问题

    • Zoned(时区):指定时区处理时间

//获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);

//获取时间的年月日
System.out.println(now.getYear() +""+ now.getMonthValue() + now.getDayOfMonth());

//解析
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse("2025-10-11 11:11:12", pattern);
System.out.println(parse);

ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);

ZoneId of = ZoneId.of("Asia/Shanghai");
System.out.println(of);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值