package com.shi.lambda; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.shi.model.Employee; /** * 初始化案例 * @author xiaoshi * */ public class _1_FirstDomo { List<Employee> employees = Arrays.asList(new Employee("张三",12,665.23), new Employee("张三",12,789.23), new Employee("张三",15,133.23), new Employee("张三",20,7884.23), new Employee("张三",30,8784.23), new Employee("张三",40,665.23)); /** * 查询年龄小于等于20岁的员工的信息 Lembda stream */ @Test public void getEmployeeByAge() { employees.stream() .filter((e) -> e.getAge()<20) .forEach(System.out::println); } /** * 查询工资大于的1000的员工信息 Lembda stream */ @Test public void getEmployeeBySalary() { employees.stream() .filter((e) -> e.getSalary()>1000) .forEach(System.out::println); } }
package com.shi.lambda; import java.util.Comparator; import java.util.function.Consumer; import org.junit.Test; /** * 一 . lambda 表达式的基础语法:JAVA8 中引用了一个新的操做符 “->” 该操做符称为箭头操做符或者叫作lambda操做符 * * 箭头操做符将lambda表达式拆封成俩部分: * 左测:lambda 表达式的参数列表 * 右侧: lambda 表达式所需执行的功能,及lambda体 * * 语法格式一:无参数,无返回值 * () -> System.out.println("hello Lambda"); * * 语法格式二:有一个参数,而且无返回值 (若是是一个参数 括号能够不写 ) * x -> System.out.println(x); * * 语法格式三:有俩个以上的参数,有返回值,而且Lambda 体中有多条语句 * Comparator<Integer> con = (x,y) -> { System.out.println("函数式接口"); return Integer.compare(x, y); }; * * 语法格式四:有俩个以上的参数,有返回值,而且Lambda 体中有只有一条语句 * Comparator<Integer> con = (x,y) -> Integer.compare(x, y); * * * 语法格式五: Lambda 表达式的参数列表的类型能够省略不写, * 由于JVM编译器 经过上下文推断出,数据类型,既“类型判断” * * 口诀: 左侧遇一括号省; * 右侧遇一return省; * 左侧推断类型省; * 右侧多条大括号; * * 二. lambda 表达式须要“函数式接口”的支持 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口 可使用@FunctionalInterface修饰(检查接口是不是函数式接口) * * @author xiaoshi * */ public class _2_lambdaTest { //无参数,无返回值 @Test public void test1() { System.out.println("-------以前的实现方式------"); Runnable r = new Runnable() { @Override public void run() { System.out.println("hello world!"); } }; r.run(); System.out.println("-------lambda的实现方式------"); Runnable r1 = () -> System.out.println("hello lambda"); r1.run(); } //有一个参数,而且无返回值 (若是是一个参数 括号能够不写 ) @Test public void test2() { Consumer<String> con = x -> System.out.println(x); con.accept("像接口中添加元素"); } //有俩个以上的参数,有返回值,而且Lambda 体中有多条语句 @Test public void test3() { Comparator<Integer> con = (x,y) -> { System.out.println("函数式接口"); return Integer.compare(x, y); }; System.out.println(con.compare(10, 12)); } //语法格式四:有俩个以上的参数,有返回值,而且Lambda 体中有只有一条语句 @Test public void test4() { Comparator<Integer> con = (x,y) -> Integer.compare(x, y); System.out.println(con.compare(10, 6)); } }
package com.shi.lambda; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.junit.Test; /** * Java8 4大核心函数式接口 * * Consumer<T> :消费型接口 (有参数,无返回值的接口) * void accept(T t); * * Supplier<T> :供给型接口(无参数,有返回值的接口) * T get(); * * Function<T,R> :函数型接口(参数T类型,返回值R类型) * R apply(T t); * * Predicate<T> : 断言型接口 (参数 T类型,返回Boolean) * boolean test(T t); * * @author xiaoshi * */ public class _3_LambdaFunction { //Consumer<T> :消费型接口 (有参数,无返回值的接口) @Test public void test1 () { Consumer<Double> con = (m) -> System.out.println("我消费"+m+"$"); con.accept(100.0);//调用接口 } //Supplier<T> :供给型接口 (无参数,有返回值的接口) @Test public void test2() { Supplier<String> supp = () -> UUID.randomUUID().toString(); System.out.println(supp.get());//调用接口 } //Function<T,R> :函数型接口 (参数T类型,返回值R类型) @Test public void test3() { //把Double转换成字符串输出 Function<Double,String> fun = (item) -> item.toString(); System.out.println(fun.apply(123.334));//调用接口 } //Predicate<T> : 断言型接口 (参数 T类型,返回Boolean) @Test public void test4() { //字符串的长度大于4则返回 Predicate<String> prd = (item) -> item.length() > 4; System.out.println(prd.test("shiye"));//调用接口 } }
package com.shi.stream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.junit.Test; import com.shi.model.Employee; /** * Stream 是一个流,不改变数据源,产生一个新的数据的流 * Stream 是一个惰性求值,延迟加载的过程 * * * 一。 Stream的三个操做步骤 * * 1. 建立stream, * 2.中间操做 * 3.终止操做(终端操做 ) * * * @author xiaoshi * */ public class _4_StreamTest { //建立stream @Test public void test1() { //1. 能够经过Collection系列集合提供的Stream(串行流) 或者 parallelStream(并行流) List<String> list = new ArrayList<>(); Stream<String> stream1 = list.stream(); //2. 经过Arrays 中的静态方法stream() 获取数组流 Employee[] emps = new Employee[10]; Stream<Employee> stream2 = Arrays.stream(emps); //3. 经过Stream类中的静态方法of() Stream<String> stream3 = Stream.of("aa","bb","cc"); //4. 建立无限流(迭代) Stream<Integer> stream4 = Stream.iterate(0, (x) -> x+2); stream4.limit(5).forEach(System.out::println); //5 使用 Stream.generate() 方法 Stream.generate(() -> Math.random()) .limit(10).forEach(System.out::println); } }
package com.shi.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.junit.Test; import com.shi.model.Employee; /** * Stream 的中间操做 * * @author xiaoshi * */ public class _5_StreamTest { List<Employee> employees = Arrays.asList(new Employee("张三",12,100.23), new Employee("李四",23,789.23), new Employee("王五",15,133.23), new Employee("赵六",8,7884.23), new Employee("田七",30,8784.23), new Employee("田七",30,8784.23), new Employee("田七",30,8784.23), new Employee("田七",30,8784.23), new Employee("刘八",40,665.23)); /** * 筛选与切片 * filter - 接收Lambda,从流中排除某些元素 * limit - 截断流,使其元素不超过给定数量 * skip(n) - 跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空值,与limit(n)互补 * distinct - 筛选,经过流中所生成元素的HashCode() 和 equals() 去除重复元素 */ @Test public void test1() { //中间操做:不会执行任何操做 System.out.println("*********** filter ************"); Stream<Employee> stream = employees.stream() .filter((e) -> { System.out.println("遍历到当前值"+e.getAge()); return e.getAge() > 20; }); //终止操做:一次性执行所有内容,既:“惰性求值” stream.forEach(System.out::println); System.out.println("---------------limit----------------"); employees.stream() .filter((e) -> { System.out.println("短路!"); return e.getSalary() > 500; }) .limit(2) .forEach(System.out::println); System.out.println("***************skip distinct**************"); employees.stream() .filter((e) -> e.getSalary()>500) .skip(2) .distinct() .forEach(System.out::println); } /** * 映射 : * map - 接收lambda,将元素转换成其余形式或者提取信息。接收一个函数做为参数, * 该函数会被应用到每一个元素上,并将映射成一个新的函数 * flatMap - 接收一个函数做为参数,将流中的每一个值都换成一个流,而后把全部流链接成一个流 */ @Test public void test2() { List<String> list = Arrays.asList("aaa","bbb","ccc"); System.out.println("************map************"); list.stream() .map((str) -> str.toUpperCase()) .forEach(System.out::println); employees.stream() .map(Employee::getName) .forEach(System.out::println); System.out.println("************flatMap************"); } /** * 排序: * sorted() - 天然排序(comparable) * sorted(Comparator comparator) - 定制排序(Comparator) */ @Test public void test3() { List<String> list = Arrays.asList("ccc","ddd","eee","aaa","bbb"); System.out.println("------------天然排序------------"); list.stream() .sorted() .forEach(System.out::println); System.out.println("------------定制排序------------"); employees.stream() .sorted((e1,e2) -> { if(e1.getAge().equals(e2.getAge())) { return e1.getName().compareTo(e2.getName()); }else { return e1.getAge().compareTo(e2.getAge()); } }).forEach(System.out::println); } /** * 查找与匹配: * allMatch - 检查匹配全部元素 * anyMatch - 匹配到任意一个元素 * noneMatch - 没有匹配到任意一个元素 */ @Test public void test4() { System.out.println("-----------allMatch-----------"); boolean allMatch = employees.stream() .allMatch((e) -> { System.out.println("匹配到但前元素" + e.getAge()); return e.getAge()< 30 ; }); System.out.println(allMatch); System.out.println("-----------anyMatch-----------"); boolean anyMatch = employees.stream() .anyMatch((e) -> { System.out.println("匹配到但前元素" + e.getAge()); return e.getAge()< 30 ; }); System.out.println(anyMatch); System.out.println("-----------noneMatch-----------"); boolean noneMatch = employees.stream() .noneMatch((e) -> { System.out.println("匹配到但前元素" + e.getAge()); return e.getAge()< 30 ; }); System.out.println(noneMatch); System.out.println("-----------findFirst-----------"); Optional<Employee> findFirst = employees.stream() .sorted((e1,e2) -> e1.getAge().compareTo(e2.getAge())) .findFirst(); System.out.println(findFirst.get()); System.out.println("-----------findAny-----------"); Optional<Employee> findAny = employees.stream() .sorted((e1,e2) -> e1.getAge().compareTo(e2.getAge())) .findAny(); System.out.println(findAny.get()); System.out.println("-----------max-----------"); Optional<Employee> max = employees.stream() .max((e1,e2) -> e1.getAge().compareTo(e2.getAge())); System.out.println(max.get()); System.out.println("-----------min-----------"); Optional<Integer> min = employees.stream() .map( Employee::getAge) .min(Integer::compareTo); //这里调用上下文中的compareTo System.out.println(min.get()); } /** * 规约 * reduce(T identity, BinaryOperator<T> accumulator)/ * reduce(BinaryOperator<T> accumulator) * - 能够将流中的元素反复结合起来,获得一个值 */ @Test public void test5() { List<Integer> list = Arrays.asList(1,2,3,4,5); System.out.println("---------reduce--------"); Integer sum = list.stream() .reduce( 0 , (x,y) -> x + y ); System.out.println(sum); System.out.println("---------reduce2--------"); Optional<Double> reduce2 = employees.stream() .map(Employee::getSalary) .reduce(Double::sum); System.out.println(reduce2.get()); } /** * 收集 : * collect - 将流转换为其余形式。接收一个Collector接口的实现,用于给Stream 中元素作汇总的方法 */ @Test public void test6() { System.out.println("********collect********"); Set<String> collect = employees.stream() .map(Employee::getName) .collect(Collectors.toSet()); //去除重复元素 System.out.println(collect); System.out.println("**********linkedHashSet**********"); LinkedHashSet<String> linkedHashSet = employees.stream() .map(Employee::getName) .collect(Collectors.toCollection(LinkedHashSet::new)); linkedHashSet.forEach(System.out::println); } }
package com.shi.frokjoin; import java.util.concurrent.RecursiveTask; /** * 简单的模拟Fork/Join框架的使用 * @author xiaoshi * */ public class ForkJoinCalculate extends RecursiveTask<Long>{ /** * */ private static final long serialVersionUID = 1L; private long start; private long end; private static final long THRESHOLD = 10000; public ForkJoinCalculate(long start,long end) { this.start = start; this.end = end; } @Override protected Long compute() { long length = end - start; if(length <= THRESHOLD) { long sum = 0; for (long i = start; i <= end; i++) { sum += i; } return sum; }else { long middle = (start + end) / 2; //迭代 ForkJoinCalculate left = new ForkJoinCalculate(start, middle); left.fork(); //拆分子任务,同时压入线程队列 ForkJoinCalculate right = new ForkJoinCalculate(middle + 1 ,end); right.fork(); return left.join() + right.join(); } } }
package com.shi.frokjoin; import java.time.Duration; import java.time.Instant; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.stream.LongStream; import org.junit.Test; /** * 效率测试 * @author xiaoshi * */ public class TestForkJoin { /** * 使用fork/join框架进行测试用时时间 * * 数据:100000000L 10000000000L * 时间: 34毫秒 1204毫秒 */ @Test public void test1() { Instant start = Instant.now(); ForkJoinPool pool = new ForkJoinPool(); ForkJoinTask<Long> task = new ForkJoinCalculate(0,10000000000L); Long sum = pool.invoke(task); System.out.println(sum); Instant end = Instant.now(); System.out.println("耗时时间为:" + Duration.between(start, end).toMillis() + "毫秒"); } /** * 使用单线程用时时间 * 数据:100000000L 10000000000L * 时间:425毫秒 27855毫秒 */ @Test public void test2() { Instant start = Instant.now(); Long sum = 0L; for(long i = 0;i < 10000000000L; i++) { sum += i; } System.out.println(sum); Instant end = Instant.now(); System.out.println("耗时时间为:" + Duration.between(start, end).toMillis() + "毫秒"); } /** * 使用JAVA 8 提供的并行流 * * 数据:100000000L 10000000000L * 时间:66毫秒 825毫秒 */ @Test public void test3() { Instant start = Instant.now(); LongStream.rangeClosed(0,10000000000L) .parallel() .reduce(0, Long::sum); Instant end = Instant.now(); System.out.println("耗时时间为:" + Duration.between(start, end).toMillis() + "毫秒"); } }
package com.shi.date; import java.time.DayOfWeek; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.Set; import org.junit.Test; /** * JAVA8 日期时间的操做 * @author xiaoshi * */ public class DateTest { /** * 获取当前时间 * LocalDate、LocalTime、LocalDateTime */ @Test public void test1() { LocalDate localDate = LocalDate.now(); System.out.println(localDate); LocalTime localTime = LocalTime.now(); System.out.println(localTime); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); } /** * 指定时间日期的转化 (不能超出时间限制) */ @Test public void test2() { LocalDate localDate = LocalDate.of(2019, 5, 18); System.out.println(localDate); LocalTime localTime = LocalTime.of(18, 29, 45); System.out.println(localTime); LocalDateTime localDateTime = LocalDateTime.of(2018, 12, 1, 23, 11, 12); System.out.println(localDateTime); } /** * 日期的加减操做(+ - ) */ @Test public void test3() { LocalDate localDate = LocalDate.now(); System.out.println("当前时间:"+localDate); System.out.println("当前时间加3天:"+localDate.plusDays(3)); System.out.println("当前时间加3个月:"+localDate.plusMonths(3)); System.out.println("当前时间加3年:"+localDate.plusYears(3)); System.out.println("当前时间加2周:"+localDate.plusWeeks(2)); System.out.println("当前时间减去3天:"+localDate.minusDays(3)); System.out.println("当前时间减去3个月:"+localDate.minusMonths(3)); System.out.println("当前时间减去3年:"+localDate.minusYears(3)); System.out.println("当前时间减去2周:"+localDate.minusWeeks(2)); } /** * 获取年月日,和时间基本判断 */ @Test public void test4() { LocalDate localDate = LocalDate.now(); System.out.println("这个月的天数:"+localDate.getDayOfMonth()); System.out.println("今年的第几天:"+localDate.getDayOfYear()); System.out.println("今天是周几:"+localDate.getDayOfWeek()); System.out.println("今天是第几月:"+localDate.getMonth()); System.out.println("今天是第几年:"+localDate.getYear()); LocalDate plusDays = localDate.plusDays(3); LocalDate minusDays = localDate.minusDays(2); System.out.println("localDate在plusDays以前:" + localDate.isBefore(plusDays)); System.out.println("localDate在minusDays以后:" + localDate.isAfter(minusDays)); System.out.println("今年是否是润年"+localDate.isLeapYear()); } /** * Duration 和 Period * Duration:用于计算两个“时间”间隔 * Period:用于计算两个“日期”间隔 */ @Test public void test5() { LocalDate localDate = LocalDate.now(); LocalDate plusDays = localDate.plusDays(10); LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime plusMinutes = localDateTime.plusMinutes(46); System.out.println("时间相差:" + Duration.between(localDateTime, plusMinutes).toMinutes() + "分钟"); System.out.println("日期相差:" + Period.between(localDate, plusDays).getDays() + "天"); } /** * 时间矫正器 * 下一个日期的指定 */ @Test public void test6() { LocalDate nextLocalDate = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY)); System.out.println("下一个周三的日期 : " + nextLocalDate); } /** * 格式化日期时间 */ @Test public void test7() { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; LocalDateTime localDateTime = LocalDateTime.now(); String now = dateTimeFormatter.format(localDateTime); System.out.println(" 根据ISO_LOCAL_DATE_TIME格式化日期 : " + now); DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"); System.out.println("指定日期格式转化 : " + ofPattern.format(localDateTime)); } /** * 获取全部时区 */ @Test public void test8() { Set<String> set = ZoneId.getAvailableZoneIds(); set.forEach(System.out::println); } /** * ZonedDate、ZonedTime、ZonedDateTime * 获取指定时区下的时间 */ @Test public void test9() { LocalDateTime localDateTime1 = LocalDateTime.now(ZoneId.of("America/Cuiaba")); System.out.println("America/Cuiaba时区下面的时间 : " + localDateTime1); LocalDateTime localDateTime2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai")); System.out.println("Asia/Shanghai时区下的时间 : " + localDateTime2); } }