13.Java8的新特性
13.1 Lambda表达式
public class Main {
@Test
public void test1(){
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("runnable1");
}
};
runnable1.run();
System.out.println("******");
Runnable runnable2=()-> System.out.println("runnable2");;
runnable2.run();
}
@Test
public void test2(){
Consumer<String> consumer1 = new Consumer<>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
consumer1.accept("consumer1");
System.out.println("******");
Consumer<String> consumer2=s-> System.out.println(s);
consumer2.accept("consumer2");
}
@Test
public void test3(){
Comparator<Integer> comparator1 = new Comparator<>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
System.out.println(comparator1.compare(12,21));
System.out.println("*******");
Comparator<Integer> comparator2 = (o1,o2) -> o1.compareTo(o2);
System.out.println(comparator2.compare(12,21));
System.out.println();
Comparator<Integer> comparator3 = new Comparator<>() {
@Override
public int compare(Integer o1, Integer o2) {
System.out.println("diudiudiudiudiu!");
return o1.compareTo(o2);
}
};
System.out.println(comparator3.compare(12,21));
System.out.println("*******");
Comparator<Integer> comparator4 = (o1,o2) -> {
System.out.println("diudiudiudiudiu!");
return o1.compareTo(o2);
};
System.out.println(comparator4.compare(12,21));
}
}
13.2 函数式接口
public class Main {
@Test
public void test1(){
Consumer<Double> consumer=a->System.out.println(a);
consumer.accept(100.0);
}
@Test
public void test2(){
Supplier<String> supplier=()->"hh";
String s = supplier.get();
System.out.println(s);
}
@Test
public void test3(){
Function<String,Integer> function=s->Integer.parseInt(s);
Integer apply = function.apply("12");
System.out.println(apply);
}
@Test
public void test4(){
List<String> list = Arrays.asList("北京", "南京", "天津", "东京", "西京", "普京");
List<String> filterString = filterString(list, s -> s.contains("京"));
for (String s : filterString) {
System.out.println(s);
}
}
public List<String> filterString(List<String> list, Predicate<String> predicate){
ArrayList<String> filterList = new ArrayList<>();
for (String s : list) {
if(predicate.test(s)) {
filterList.add(s);
}
}
return filterList;
}
}
13.3 方法引用
public class Main {
@Test
public void test1() {
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("con1");
System.out.println("*******************");
Consumer<String> con2=System.out::println;
con2.accept("con2");
}
@Test
public void test2() {
Employee emp = new Employee(1001,"Tom",23,5600);
Supplier<String> sup1 = () -> emp.getName();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<String> sup2=emp::getName;
System.out.println(sup2.get());
}
@Test
public void test3() {
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(12,21));
System.out.println("*******************");
Comparator<Integer> com2=Integer::compare;
System.out.println(com2.compare(12, 21));
}
@Test
public void test4() {
Function<Double,Long> func1 = d -> Math.round(d);
System.out.println(func1.apply(12.3));
System.out.println("*******************");
Function<Double,Long> func2=Math::round;
System.out.println(func2.apply(12.3));
}
@Test
public void test5() {
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc","abd"));
System.out.println("*******************");
Comparator<String> com2=String::compareTo;
System.out.println(com2.compare("abc","abd"));
}
@Test
public void test6() {
BiPredicate<String,String> pre1 = (s1, s2) -> s1.equals(s2);
System.out.println(pre1.test("abc","abc"));
System.out.println("*******************");
BiPredicate<String,String> pre2 = String :: equals;
System.out.println(pre2.test("abc","abd"));
}
@Test
public void test7() {
Employee employee = new Employee(1001, "Jerry", 23, 6000);
Function<Employee,String> func1 = e -> e.getName();
System.out.println(func1.apply(employee));
System.out.println("*******************");
Function<Employee,String> func2 = Employee::getName;
System.out.println(func2.apply(employee));
}
}
class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee() {
System.out.println("Employee().....");
}
public Employee(int id) {
this.id = id;
System.out.println("Employee(int id).....");
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
if (id != employee.id)
return false;
if (age != employee.age)
return false;
if (Double.compare(employee.salary, salary) != 0)
return false;
return name != null ? name.equals(employee.name) : employee.name == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
13.4 构造器引用与数组引用
public class Main {
@Test
public void test1(){
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<Employee> sup2 = Employee :: new;
System.out.println(sup2.get());
}
@Test
public void test2(){
Function<Integer,Employee> func1 = id -> new Employee(id);
Employee employee = func1.apply(1001);
System.out.println(employee);
System.out.println("*******************");
Function<Integer,Employee> func2 = Employee :: new;
Employee employee1 = func2.apply(1002);
System.out.println(employee1);
}
@Test
public void test3(){
BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
System.out.println(func1.apply(1001,"Tom"));
System.out.println("*******************");
BiFunction<Integer,String,Employee> func2 = Employee :: new;
System.out.println(func2.apply(1002,"Tom"));
}
@Test
public void test4(){
Function<Integer,String[]> func1 = length -> new String[length];
String[] arr1 = func1.apply(5);
System.out.println(Arrays.toString(arr1));
System.out.println("*******************");
Function<Integer,String[]> func2=String[] :: new;
String[] arr2 = func2.apply(10);
System.out.println(Arrays.toString(arr2));
}
}
class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee() {
System.out.println("Employee().....");
}
public Employee(int id) {
this.id = id;
System.out.println("Employee(int id).....");
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
if (id != employee.id)
return false;
if (age != employee.age)
return false;
if (Double.compare(employee.salary, salary) != 0)
return false;
return name != null ? name.equals(employee.name) : employee.name == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
13.5 Stream API
public class Main {
@Test
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
Stream<Employee> stream = employees.stream();
Stream<Employee> parallelStream = employees.parallelStream();
}
@Test
public void test2(){
int[] arr=new int[]{1,2,3,4,5,6};
IntStream stream = Arrays.stream(arr);
Employee e1 = new Employee(1001, "Tom");
Employee e2 = new Employee(1002, "Jerry");
Employee[] arr1=new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}
@Test
public void test4(){
Stream.iterate(0,t->t+2).limit(10).forEach(System.out::println);
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
@Test
public void test5(){
List<Employee> employees = EmployeeData.getEmployees();
Stream<Employee> stream = employees.stream();
stream.filter(e->e.getSalary()>7000).forEach(System.out::println);
employees.stream().limit(3).forEach(System.out::println);
employees.stream().skip(3).forEach(System.out::println);
employees.add(new Employee(1010,"刘强东",40,8000));
employees.add(new Employee(1010,"刘强东",40,8000));
employees.add(new Employee(1010,"刘强东",40,8000));
employees.add(new Employee(1010,"刘强东",40,8000));
employees.add(new Employee(1010,"刘强东",40,8000));
employees.add(new Employee(1010,"刘强东",40,8000));
employees.stream().distinct().forEach(System.out::println);
}
@Test
public void test6(){
List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
list.stream().map(str->str.toUpperCase()).forEach(System.out::println);
List<Employee> employees = EmployeeData.getEmployees();
Stream<String> namesStream = employees.stream().map(Employee::getName);
namesStream.filter(name->name.length()>3).forEach(System.out::println);
Stream<Stream<Character>> streamStream = list.stream().map(Main::fromStringToStream);
streamStream.forEach(s->s.forEach(System.out::println));
System.out.println();
Stream<Character> characterStream = list.stream().flatMap(Main::fromStringToStream);
characterStream.forEach(System.out::println);
}
public static Stream<Character> fromStringToStream(String str){
ArrayList<Character> list = new ArrayList<>();
for(Character c : str.toCharArray()){
list.add(c);
}
return list.stream();
}
@Test
public void test7(){
List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
list.stream().sorted().forEach(System.out::println);
List<Employee> employees = EmployeeData.getEmployees();
employees.stream().sorted((e1,e2)->{
int ageValue=Integer.compare(e1.getAge(),e2.getAge());
if(ageValue!=0){
return ageValue;
}else {
return -Double.compare(e1.getSalary(),e2.getSalary());
}
}).forEach(System.out::println);
}
@Test
public void test8(){
List<Employee> employees = EmployeeData.getEmployees();
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
Optional<Employee> employee = employees.stream().findFirst();
Optional<Employee> employee1 = employees.parallelStream().findAny();
long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
Optional<Double> maxSalary = salaryStream.max(Double::compare);
Optional<Employee> employee2 = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
employees.stream().forEach(System.out::println);
employees.forEach(System.out::println);
}
@Test
public void test9(){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer sum = list.stream().reduce(10, Integer::sum);
List<Employee> employees = EmployeeData.getEmployees();
Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
}
@Test
public void test10(){
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
employeeList.forEach(System.out::println);
System.out.println();
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
}
}
class EmployeeData {
public static List<Employee> getEmployees(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 12, 9876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
return list;
}
}
class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee() {
System.out.println("Employee().....");
}
public Employee(int id) {
this.id = id;
System.out.println("Employee(int id).....");
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
if (id != employee.id)
return false;
if (age != employee.age)
return false;
if (Double.compare(employee.salary, salary) != 0)
return false;
return name != null ? name.equals(employee.name) : employee.name == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
13.6 Optional类的使用
public class Main {
@Test
public void test1(){
Optional<Object> op1 = Optional.empty();
System.out.println(op1);
if(!op1.isPresent()){
System.out.println("数据为空");
}
}
@Test
public void test2(){
Girl girl = new Girl();
Optional<Girl> optionalGirl = Optional.of(girl);
System.out.println(optionalGirl.get());
}
@Test
public void test3(){
Girl girl = new Girl();
girl=null;
Optional<Girl> optionalGirl = Optional.ofNullable(girl);
System.out.println(optionalGirl);
Girl girl1 = optionalGirl.orElse(new Girl("迪丽热巴"));
System.out.println(girl1);
}
@Test
public void test4(){
Boy boy=null;
String girlName = getGirlName2(boy);
System.out.println(girlName);
boy=new Boy();
String girlName1 = getGirlName2(boy);
System.out.println(girlName1);
boy=new Boy(new Girl("苍老师"));
String girlName2 = getGirlName2(boy);
System.out.println(girlName2);
}
public String getGirlName(Boy boy){
return boy.getGirl().getName();
}
public String getGirlName1(Boy boy){
if(boy!=null){
Girl girl = boy.getGirl();
if(girl!=null){
return girl.getName();
}
}
return null;
}
public String getGirlName2(Boy boy){
Optional<Boy> boyOptional = Optional.ofNullable(boy);
Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));
Girl girl = boy1.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));
return girl1.getName();
}
}
class Girl {
private String name;
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Girl() {
}
public Girl(String name) {
this.name = name;
}
}
class Boy {
private Girl girl;
@Override
public String toString() {
return "Boy{" +
"girl=" + girl +
'}';
}
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
public Boy() {
}
public Boy(Girl girl) {
this.girl = girl;
}
}