java8
Employee;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private int age;
private String name;
private double salary;
@Override
public String toString() {
return "Employee{" +
"age=" + age +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
FilterEmpByAge:
public class FilterEmpByAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee t) {
return t.getAge()>=35;
}
}
FilterEmpBysalary:
public class FilterEmpBysalary implements MyPredicate<Employee>{
@Override
public boolean test(Employee t) {
return t.getSalary()>=500;
}
}
ForkJoin:
package com.example.java8;
import java.util.concurrent.RecursiveTask;
/**
* 要使用Fork Join,必须继承RecursiveAction(无返回值)或RecursiveTask(有返回值)
*/
public class ForkJoin extends RecursiveTask<Long> {
private static final long serialVersionUID = 1L;
private long start;
private long end;
/**
* 临界值
*/
private static final long THER = 10000;
public ForkJoin(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long length = end - start;
if (length <= THER) {
long sum = 0;
for (long i = start; i < end; i++) {
sum += i;
}
return sum;
} else {
long a = (start + end) / 2;
ForkJoin left = new ForkJoin(start, a);
left.fork(); //拆分成子任务
ForkJoin right = new ForkJoin(a + 1, end);
right.fork(); //拆分成子任务
return left.join() + right.join();
}
}
}
ForkJoinTest
package com.example.java8;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class ForkJoinTest {
/**
* fork jion框架
*/
@Test
public void test() {
Instant start = Instant.now();//java8的计算时间
ForkJoinPool forkJoinPool = new ForkJoinPool();//创建线程池
ForkJoinTask<Long> task = new ForkJoin(0, 100000000L);
Long sum = forkJoinPool.invoke(task);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗时" + Duration.between(start, end).toMillis());
}
@Test
public void test1() {
Instant start = Instant.now();//java8的计算时间
Long sum = 0L;
for (int i = 0; i <= 100000000; i++) {
sum += i;
}
System.out.println(sum);
Instant end = Instant.now();
System.out.println("耗时" + Duration.between(start, end).toMillis());
}
/**
* java8的
* 并行流 :parallel():底层是forkjoin
* 顺序流:sequential()
*/
@Test
public void test2() {
Instant start = Instant.now();
System.out.println(LongStream.rangeClosed(0, 100000000L)
.parallel() //调用并行流 :parallel()
.reduce(0, Long::sum));
Instant end = Instant.now();
System.out.println("耗时:" +Duration.between(start,end).toMillis());
}
@Test
public void test3() {
Instant start = Instant.now();
System.out.println(LongStream.rangeClosed(0, 100000000L)
.sequential() //调用并行流 :parallel()
.reduce(0, Long::sum));
Instant end = Instant.now();
System.out.println("耗时:" +Duration.between(start,end).toMillis());
}
}
Godness
package com.example.java8;
import lombok.*;
@Data
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Godness {
private String name;
@Override
public String toString() {
return "Godness{" +
"name='" + name + '\'' +
'}';
}
}
Man
package com.example.java8;
public class Man {
private Godness godness;
public Man(){
super();
}
public Man(Godness godness) {
super();
this.godness = godness;
}
public Godness getGodness() {
return godness;
}
public void setGodness(Godness godness) {
this.godness = godness;
}
@Override
public String toString() {
return "Man{" +
"godness=" + godness +
'}';
}
}
ManNew
package com.example.java8;
import lombok.*;
import java.util.Optional;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ManNew {
private Optional<Godness> godness = Optional.empty();
public void setGodness(Optional<Godness> godness) {
this.godness = godness;
}
public Optional<Godness> getGodness() {
return godness;
}
@Override
public String toString() {
return "ManNew{" +
"godness=" + godness +
'}';
}
}
MyClass
package com.example.java8;
public class MyClass {
public String getname(){
return "MyClass";
}
}
MyFun
package com.example.java8;
public interface MyFun {
default String getname(){
return "Myfun";
}
public static void show(){
System.out.println("静态");
}
}
MyPredicate
package com.example.java8;
public interface MyPredicate<T> {
public boolean test( T t);
}
StreamAPI1
package com.example.java8;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 一、stream操作三步:
* 1.创建stream
* 4种方式
* 2.中间操作:像limit
* 3.终止操作:像foreach
* 注意:多个中间操作可以连接起来形成一个流水线 ,除非流水线上触发终止操作,和否则中间操作不会执行任何的处理。
* 终止操作一次性全部操作,称为惰性求值
*/
public class StreamAPI1 {
@Test
public void test() {
//创建stream的4中方式
//tongguo Collection系列提供的stream()或parallelStream()
List<String> list = new ArrayList<>();
final Stream<String> stream = list.stream();
//通过Arrays中的静态stream()获取数组流
Employee[] emp = new Employee[10];
Stream<Employee> stream1 = Arrays.stream(emp);
//通过Stream中的静态方法of
Stream<String> a = Stream.of("a", "b", "ww");
//创建无限流
Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
iterate.limit(10).forEach(System.out::println);
Stream.generate(() -> Math.random()).limit(10).forEach(System.out::println);
}
/**
* 对象转集合
*/
List<Employee> employees = Arrays.asList(
new Employee(18, "zs", 999.22),
new Employee(15, "ww", 599.22),
new Employee(19, "zl", 259.22),
new Employee(55, "cq", 111.22),
new Employee(45, "er", 11.22)
);
/**
* 映射
* map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
* flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
*/
@Test
public void test1() {
List<String> list = Arrays.asList("wer", "wre", "yuidfg", "hjk");
list.stream()
.map((s) -> s.toUpperCase())
.limit(3)
.forEach(System.out::println);
employees.stream()
.map(Employee::getName)
.forEach(System.out::println);
Stream<Stream<Character>> sma = list.stream()
.map(StreamAPI1::fiCher);
sma.forEach(x -> x.forEach(System.out::println));
//flatMap
Stream<Character> sm = list.stream()
.flatMap(StreamAPI1::fiCher);
sm.forEach(System.out::println);
}
public static Stream<Character> fiCher(String string) {
List<Character> list = new ArrayList<>();
for (Character character : string.toCharArray()) {
list.add(character);
}
return list.stream();
}
/**
* sorted():自然排序,流中元素需实现Comparable接口
* sorted(Comparator com):定制排序,自定义Comparator排序器
*/
@Test
public void test2() {
List<String> list = Arrays.asList("aa", "ff", "dd");
//String 类自身已实现Compareable接口
list.stream().sorted().forEach(System.out::println);// aa dd ff
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
//自定义排序:先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o1.getAge() - o2.getAge();
} else {
return o1.getName().compareTo(o2.getName());
}
}
).forEach(System.out::println);
}
/**
* peek:如同于map,能得到流中的每一个元素。但map接收的是一
* 个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。
*/
@Test
public void test3() {
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream()
.peek(o -> o.setAge(100))
.forEach(System.out::println);
}
/**
* 终止操作:
* allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
* noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
* anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
* findFirst:返回流中第一个元素
* findAny:返回流中的任意元素:可以看到findAny()操作,返回的元素是不确定的,对于同一个列表多次调用findAny()有可能会返回不同的值。使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行的情况,那就不能确保是第一个
* count:返回流中元素的总个数
* max:返回流中元素最大值
* min:返回流中元素最小值
*/
@Test
public void test4() {
List<Integer> list = Arrays.asList(2, 3, 4, 5);
boolean allMatch = list.stream().allMatch(e -> e > 10); //false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
boolean anyMatch = list.stream().anyMatch(e -> e > 4); //true
Integer findFirst = list.stream().findFirst().get(); //1
Integer findAny = list.stream().findAny().get(); //
long count = list.stream().count(); //5
Integer max = list.stream().max(Integer::compareTo).get(); //5
Integer min = list.stream().min(Integer::compareTo).get(); //1
System.out.println(allMatch);
System.out.println(noneMatch);
System.out.println(anyMatch);
System.out.println(findFirst);
System.out.println(findAny);
System.out.println(count);
System.out.println(max);
System.out.println(min);
}
/**
* 规约操作
* Optional<T> reduce(BinaryOperator<T> accumulator):第一次执行时,
* accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,
* 第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
* T reduce(T identity, BinaryOperator<T> accumulator):流程跟上面一样,只是第一次执行时,
* accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
* <U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner):在串行流(stream)中,
* 该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,
* 此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当
* 成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。
*/
@Test
public void test5() {
Optional<Double> reduce = employees.stream().map(Employee::getSalary).reduce(Double::sum);
System.out.println(reduce.get());
Set<String> collect = employees.stream().map(Employee::getName).collect(Collectors.toSet());
collect.forEach(System.out::println);
//经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
System.out.println(v); // 55
Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
System.out.println(v1); //65
Integer v2 = list.stream().reduce(0,
(x1, x2) -> {
System.out.println("stream accumulator: x1:" + x1 + " x2:" + x2);
return x1 - x2;
},
(x1, x2) -> {
System.out.println("stream combiner: x1:" + x1 + " x2:" + x2);
return x1 * x2;
});
System.out.println(v2); // -300
Integer v3 = list.parallelStream().reduce(0,
(x1, x2) -> {
System.out.println("parallelStream accumulator: x1:" + x1 + " x2:" + x2);
return x1 - x2;
},
(x1, x2) -> {
System.out.println("parallelStream combiner: x1:" + x1 + " x2:" + x2);
return x1 * x2;
});
System.out.println(v3); //197474048
}
}
Student
package com.example.java8;
import lombok.*;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Student {
private String name;
private int age;
}
Subclass
package com.example.java8;
public class Subclass extends MyClass implements MyFun {
}
TestInterface
package com.example.java8;
public class TestInterface {
/**
* 类优先:
* 1。如果一个类同时继承了类和实现了接口,类和接口中都有同名方法,类优先
* 2.如果一个类同时实现了两个接口,两个接口中存在同名函数(不管方法
* 是否是默认方法 ) ,必须重写指定用哪个
*
* */
public static void main(String[] args) {
Subclass sc = new Subclass();
System.out.println(sc.getname());
MyFun.show();
}
}
TestLambad
package com.example.java8;
import org.junit.Test;
import java.util.*;
public class TestLambad {
@Test
public void test0() {
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
};
TreeSet<Integer> treeSet = new TreeSet<>(comparator);
}
//Lanbad
@Test
public void test1() {
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
TreeSet<Integer> treeSet = new TreeSet<>(comparator);
}
/**
* 对象转集合
*/
List<Employee> employees = Arrays.asList(
new Employee(18, "zs", 999.22),
new Employee(15, "ww", 599.22),
new Employee(19, "zl", 259.22),
new Employee(55, "cq", 111.22),
new Employee(45, "er", 11.22)
);
/*************************************
* 需求1:获取Employee年龄大于35的员工
*/
@Test
public void test03() {
List<Employee> list = feliterEmp(employees);
for (Employee employee : list) {
System.out.println(employee);
}
}
/**
* 把大于等于35的选出来添加到新集合
*/
public List<Employee> feliterEmp(List<Employee> list) {
List<Employee> emps = new ArrayList<>();
for (Employee emp : list) {
if (emp.getAge() >= 35) {
emps.add(emp);
}
}
return emps;
}
/****************************
* 需求1:获取Employee年工资大于500的员工
*/
@Test
public void test04() {
List<Employee> list = filterEmp1(employees);
for (Employee employee : list) {
System.out.println(employee);
}
}
public List<Employee> filterEmp1(List<Employee> list) {
List<Employee> emps = new ArrayList<>();
for (Employee emp : list) {
if (emp.getSalary() >= 500) {
emps.add(emp);
}
}
return emps;
}
/*******************************************
* 优化方式1:策略设计模式
* */
@Test
public void test05() {
//按年龄过滤
List<Employee> list = filterEmployee(this.employees, new FilterEmpByAge());
for (Employee employee : list) {
System.out.println(employee);
}
//按工资过滤
List<Employee> list1 = filterEmployee(this.employees, new FilterEmpBysalary());
for (Employee employee : list1) {
System.out.println(employee);
}
}
public List<Employee> filterEmployee(List<Employee> list, MyPredicate<Employee> mp) {
List<Employee> emps = new ArrayList<>();
for (Employee employee : list) {
if (mp.test(employee)) {
emps.add(employee);
}
}
return emps;
}
/*******************************************
* 优化方式2:匿名内部类
* */
@Test
public void test06() {
List<Employee> list = filterEmployee(employees, new MyPredicate<Employee>() {
@Override
public boolean test(Employee t) {
return t.getSalary() >= 500;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
/*******************************************
* 优化方式3:lambad
* */
@Test
public void test07() {
List<Employee> list = filterEmployee(employees, (e) -> e.getSalary() >= 500);
list.forEach(System.out::println);
}
/*******************************************
* 优化方式4:什么都没有,就有个对象和30行的对象转集合
* */
@Test
public void test08() {
employees.stream()
.filter((e) -> e.getSalary() >= 500)
.limit(2)//取前两条数据
.forEach(System.out::println);
}
}
TestMethodRef
package com.example.java8;
import org.junit.Test;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.Locale;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* 一、方法引用:若lambad体中的内容方法已经实现了,可以使用方法引用:
* 三种格式:
* 对象::实例方法名
* 类::静态方法名
* 类::实例方法名:有俩参数,如果说第一个参数是实例方法的调用者,第二个参数是实例方法的参数时
* 注意:
* 1.lambad的参数类型和返回值类型与函数式接口中保持一致
* 2.实例方法名:有俩参数,如果说第一个参数是实例方法的调用者,第二个参数是实例方法的参数时
*
* 二、构造器引用:
* 三、数组引用:其实数组也是对象
*/
public class TestMethodRef {
@Test
public void test() {
PrintStream printStream1 = System.out;
Consumer<String> consumer = x -> printStream1.println(x);
//对象::实例方法名
PrintStream printStream = System.out;
Consumer<String> consumer1 = printStream::println;
Consumer<String> consumer2 = System.out::println;
consumer.accept("qwer");
consumer1.accept("fdsjgh");
consumer2.accept("wert");
}
@Test
public void test1() {
Employee employee = new Employee();
Supplier<String> sup = () -> employee.getName();
String str = sup.get();
System.out.println(str);
//对象::实例方法名
Supplier<Integer> sup2 = employee::getAge;
Integer integer = sup2.get();
System.out.println(integer);
}
//类::静态方法名
@Test
public void test2() {
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
//compare的参数类型和返回值类型与Comparator保持一致
Comparator<Integer> com = Integer::compare;
}
//类::实例方法名:有俩参数,如果说第一个参数是实例方法的调用者,第二个参数是实例方法的参数时
@Test
public void test3() {
BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
BiPredicate<String, String> biPredicate1 = String::equals;
}
//构造器引用:
@Test
public void test4() {
Supplier<Employee> supplier = () -> new Employee();
//构造器引用:
Supplier<Employee> supplier1 = Employee::new;
Employee employee = supplier1.get();
System.out.println(employee);
}
//数组引用:
@Test
public void test5() {
Function<Integer, String[]> function = x -> new String[x];
String[] apply = function.apply(10);
System.out.println(apply.length);
Function<Integer, String[]> function1 = String[]::new;
String[] strings = function1.apply(20);
System.out.println(strings.length);
}
@Test
public void test7() {
String testString = "ii";
System.out.println(testString.toUpperCase(Locale.ROOT));
String testString2 = String.format(Locale.ROOT, "%d", 6);
System.out.println(testString2);
String str=null;
str=String.format(Locale.ROOT,"Hi,%s:%s.%s"+"Hi:%s", "王南","王力","王张","4445");
System.out.println(str);
str=String.format(Locale.ROOT,"Hi,%s", "王力");
System.out.println(str);
str=String.format(Locale.ROOT,"Hi,%s:%s.%s", "王南","王力","王张");
System.out.println(str);
System.out.printf(Locale.ROOT,"字母a的大写是:%c %n", 'A');
System.out.printf("3>7的结果是:%b %n", 3>7);
System.out.printf("100的一半是:%d %n", 100/2);
System.out.printf("100的16进制数是:%x %n", 100);
System.out.printf("100的8进制数是:%o %n", 100);
System.out.printf("50元的书打8.5折扣是:%f 元%n", 50*0.85);
System.out.printf("上面价格的16进制数是:%a %n", 50*0.85);
System.out.printf("上面价格的指数表示:%e %n", 50*0.85);
System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", 50*0.85);
System.out.printf("上面的折扣是%d%% %n", 85);
System.out.printf("字母A的散列码是:%h %n", 'A');
}
}
TestOptional
package com.example.java8;
import org.junit.Test;
import java.util.Optional;
public class TestOptional {
/**
* Optional的常用方法:
* Optional.for(T t) :创建一个Optional的实例
* Optional.empty() :创建一个空的Optional的实例
* Optional.ofNullable(T t):若t不为null,创建Optiona实例,否则创建空实例
* isPresent():判断是否包含值
* orElse(T t):如果调用对象包含值,则返回值t
* orElseGet(Supplier s):如果调用对象包含值,返回该值,否则返回s获取的值
* map(Function f):如果有值对其处理,并返回处理后的Optional.empty
* flatMap(Function mapper):与map相似,要求返回值必须是Optional
*/
/**
* 构建空1:可以锁定问题所在
*/
@Test
public void test() {
Optional<Employee> empty = Optional.empty();
System.out.println(empty.get());
}
/**
* 构建空2ofNullable(null):可以锁定问题所在
* return value == null ? empty() : of(value);
*/
@Test
public void test0() {
Optional<Employee> empty = Optional.ofNullable(new Employee());
if (empty.isPresent()) { //isPresent():判断是否包含值,有值就获取,没值什么都不做
System.out.println(empty.get());
}
/* Employee employee = empty.orElse(new Employee("张三", 12, 555.88, ObjectInputFilter.Status.FREE));
System.out.println(employee);*/
Employee employee = empty.orElse(null);
System.out.println(employee);
Employee emp = empty.orElseGet(() -> new Employee());
System.out.println(emp);
}
@Test
public void test1() {
Optional<Employee> op = Optional.of(new Employee());
Employee employee = op.get();
System.out.println(employee);
}
@Test
public void test2() {
/* Man man = new Man();
String s = getGodnessName1(man);
System.out.println(s);*/
Optional<ManNew> manNew = Optional.ofNullable(null);
String godnessNameNew = getGodnessNameNew(manNew);
System.out.println(godnessNameNew);
}
/**
* 獲取女神的名字:空指針异常
*/
/*public String getGodnessName(Man man) {
return man.getGodness().getName();
}*/
/**
* 普通的解决空指针
*/
public String getGodnessName1(Man man) {
if(man!=null){
Godness gn = man.getGodness();
if (gn!=null){
return gn.getName();
}
}
return "仓";
}
/**
* Optional解决空指针
*/
public String getGodnessNameNew(Optional<ManNew> manNew) {
return manNew.orElse(new ManNew()) //如果传入的ManNe为null,new一个
.getGodness()
.orElse(new Godness("仓仓"))
.getName();
}
}
https://blog.csdn.net/y_k_y/article/details/84633001
https://blog.csdn.net/pan_junbiao/article/details/105936470
https://blog.csdn.net/qq_37438740/article/details/81556733