java8有哪些新特性

2024-10-12 20:18:55

1、Lambda表达式:java8引入了一个新的操作符"->",该操作符将表达式拆分为两部分:左侧:Lambada表示表达式的参数列表右侧:Lambda表示所需要执行的功能@Test public void test2() { Consumer<String> consumer = (x) -> System.out.println(x); consumer.accept("我是帅哥"); }

java8有哪些新特性

2、函数式接口package com.gwolf;@FunctionalInterfacepublic interface MyPredicate<T> { public boolean test(T t);}

java8有哪些新特性

4、Stream API流式计算Stream API是java8中处理集合的蔡龇呶挞关键抽象概念,它可以指定您希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。package com.gwolf;import com.gwolf.vo.Dept;import org.junit.Test;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class TestStreamAPI { @Test public void test1() { //可以通过Collection系列集合提供提供的Stream()或parallelStream List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); //通过Arrays中的静态方法stream()方法得到数组流 Dept[] depts = new Dept[10]; Stream<Dept> deptStream = Arrays.stream(depts); }}

java8有哪些新特性

6、新日期APIpackage com.gwolf;import java.time.LocalDate;import java.time.Period;import java.time.for罪焐芡拂mat.DateTimeFormatter;import java.time.temporal.ChronoUnit;public class DateUtils { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println("今天的日期:" + today); //明天的日期 LocalDate tomrrow = today.plus(1, ChronoUnit.DAYS); System.out.println("明天的日期:" + tomrrow); System.out.println("日期" + tomrrow + "是否在" + today +"之后" + tomrrow.isAfter(today)); System.out.println("日期" + tomrrow + "是否在" + today +"之前" + tomrrow.isBefore(today)); } public static LocalDate plus(LocalDate localDate, int between,ChronoUnit chronoUnit) { return localDate.plus(between,chronoUnit); } /** * 格式化日期 * @param localDate * @param pattern * @return */ public static String parseDate(LocalDate localDate,String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return localDate.format(dateTimeFormatter); } /** * 比较两个时间相差的月份 * @param one * @param two * @return */ public static Integer between(LocalDate one,LocalDate two) { return Period.between(one,two).getMonths(); } /** * 字符串转化成日期 * @param strDate * @param pattern * @return */ public static LocalDate formatDate(String strDate,String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return LocalDate.parse(strDate,dateTimeFormatter); }}

java8有哪些新特性
猜你喜欢