java8新特性

本文深入探讨了Java8的一些核心特性,包括Lambda表达式的使用,如过滤和映射操作;引用的运用,如System.out::println;函数式接口的概念及其在Predicate中的应用;Stream流处理的示例;Optional类解决空指针异常的场景;以及新引入的日期和时间API的使用。此外,还介绍了Base64编码和解码的基本操作。
摘要由CSDN通过智能技术生成

java8新特性

public class TestApplicaiton {

public static void main(String[] args) {
    test7();
}

/**
 * java8新特性--lambda表达式
 * lambda表达式的使用
 */
private static void test1() {
    //    流的处理
    ArrayList<String> list = new ArrayList<>();
    list.add("1");
    list.add("12");
    list.add("133");
    list.add("133");
    list.add("11112");
    list.add("1333222");
    list.add("111122");
    System.out.println(list.size());
    // 可以筛选数据后并返回
    list.stream().filter(item -> item.length() < 5).collect(Collectors.toList()).forEach(System.out::println);
    System.out.println(list.size());
    // 可以筛选数据后并返回
    list.stream().map(item -> {
        if(item.length() < 5)return "qqq";
        return item;
    }).distinct().collect(Collectors.toList()).forEach(System.out::println);
    System.out.println(list.size());
}

/**
 * java8新特性--引用
 * ::双冒号代表引用, 类::方法
 * 如System.out::println 就可以实现换行打印
 */
public void test2(){
    ArrayList<String> list = new ArrayList<>();
    list.add("alipay");
    list.add("alipay");
    list.add("alipay");
    list.add("alipay");
    list.add("alipay");
  	// System.out.println();
    list.forEach(System.out::println);
}

/**
 * java8新特性--函数式接口
 * 用@FunctionalInterface注解来自定义函数式接口
 * 这个接口可以用lambda表达式来实现
 * 有且仅有一个抽象方法
 */
@FunctionalInterface
interface GreetingService
{
    void sayMessage(String message);
}

/**
 * java8新特性--函数式接口Predicate
 * 函数式接口Predicate
 */
public static void test3(){
	// predicate有一个test方法,下面的意思就是说predicate.test方法的值就是n -> true 整个方法返回的结果
    Predicate<Integer> predicate = n -> true;
    Predicate<Integer> predicate2 = n -> n>2;
    if(predicate.test(3)){
        System.out.println("3存在");
    }
    if(predicate.test(null)){
        System.out.println("null存在");
    }
    if(predicate2.test(3)){
        System.out.println("3大于2");
    }

    // lambda表达式的方式来实现函数式接口,默认把有且仅有一个抽象的方法用n -> System.out.println(n)实现
    GreetingService greetingService = n -> System.out.println(n);
    // 实现后就是sayMessage的功能变成了System.out.println(n)
    greetingService.sayMessage("a");

}

/**
 * java8新特性--stream流处理
 * +--------------------+       +------+   +------+   +---+   +-------+
 * | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
 * +--------------------+       +------+   +------+   +---+   +-------+
 */
public static void test4(){
    ArrayList<Widget> widgets = new ArrayList<>();
    widgets.add(new Widget("red", 1));
    widgets.add(new Widget("red", 2));
    widgets.add(new Widget("blue", 4));

    List<Integer> transactionsIds =
            Collections.singletonList(widgets.stream()
                    .filter(b -> b.getColor().equals("red"))
                    .sorted((x, y) -> x.getWeight() - y.getWeight())
                    .mapToInt(Widget::getWeight)
                    .sum());
    transactionsIds.forEach(System.out::println);
}

/**
 * java8新特性--Optional类
 * Optional 类的引入很好的解决空指针异常
 */
public static void test5(){
    Integer value1 = null;
    Integer value2 = 2;

    // Optional.ofNullable - 允许传递为 null 参数
    Optional<Integer> a = Optional.ofNullable(value1);

    // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
    Optional<Integer> b = Optional.of(value2);
    System.out.println(sum(a,b));
}

public static Integer sum(Optional<Integer> a, Optional<Integer> b){

    // Optional.isPresent - 判断值是否存在

    System.out.println("第一个参数值存在: " + a.isPresent());
    System.out.println("第二个参数值存在: " + b.isPresent());

    // Optional.orElse - 如果值存在,返回它,否则返回默认值
    Integer value1 = a.orElse(new Integer(0));

    //Optional.get - 获取值,值需要存在
    Integer value2 = b.get();
    return value1 + value2;
}

/**
 * java8新特性--日期时间 API
 * 旧的日期时间已经被弃用了,旧的是线程不安全的,且时区处理麻烦
 */
public static void test6(){
    // 获取当前的日期时间
    LocalDateTime currentTime = LocalDateTime.now();
    System.out.println("当前时间: " + currentTime);

    LocalDate date1 = currentTime.toLocalDate();
    System.out.println("date1: " + date1);

    Month month = currentTime.getMonth();
    int day = currentTime.getDayOfMonth();
    int seconds = currentTime.getSecond();

    System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);

    LocalDateTime date2 = currentTime.withDayOfMonth(5).withYear(2021);
    System.out.println("date2: " + date2);

    // 12 december 2021
    LocalDate date3 = LocalDate.of(2021, Month.DECEMBER, 12);
    System.out.println("date3: " + date3);

    // 22 小时 15 分钟
    LocalTime date4 = LocalTime.of(22, 15);
    System.out.println("date4: " + date4);

    // 解析字符串
    LocalTime date5 = LocalTime.parse("20:15:30");
    System.out.println("date5: " + date5);
}

/**
 * java8新特性--Base64
 */
public static void test7(){
    try {

        // 使用基本编码
        String base64encodedString = Base64.getEncoder().encodeToString("runoob?java8".getBytes("utf-8"));
        System.out.println("Base64 编码字符串 (基本) :" + base64encodedString);

        // 解码
        byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);

        System.out.println("原始字符串: " + new String(base64decodedBytes, "utf-8"));
        base64encodedString = Base64.getUrlEncoder().encodeToString("runoob?java8".getBytes("utf-8"));
        System.out.println("Base64 编码字符串 (URL) :" + base64encodedString);

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < 10; ++i) {
            stringBuilder.append(UUID.randomUUID().toString());
        }

        byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
        String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
        System.out.println("Base64 编码字符串 (MIME) :" + mimeEncodedString);

    }catch(UnsupportedEncodingException e){
        System.out.println("Error :" + e.getMessage());
    }
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值