package test.testThread.jvm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/** 四大函数式接口、链式编程、流式计算
* @author *cruder
* @version 1.0
* @since 2021/1/17 14:07
*/
public class Demo01 {
public static void main(String[] args) {
Book book1 = new Book(1,"java",50.36d);
Book book2 = new Book(2,"c++",60.68d);
Book book3 = new Book(3,"c primer",70.36d);
Book book4 = new Book();
book4.setId(4).setBookName("Python").setPrice(71.20d);
System.out.println(book1);
List<Book> bookList = Arrays.asList(book1,book2,book3,book4);
System.out.println(bookList);
bookList.stream().filter(u->{return u.getId() %2 == 0;})
.filter(t->{return t.getPrice() > 51.36d; })
.sorted((o1,o2)->{return o1.comparePrice(o2.getPrice(),o1.getPrice());})
.map(x->{return x.getBookName().toUpperCase();})
.limit(1)
.forEach(System.out::println);
List<Integer> integerList = Arrays.asList(1,2,3);
integerList = integerList.stream().map(x -> {return x*2;}).collect(Collectors.toList());
for(Integer integer:integerList){
System.out.println(integer);
}
/**
* 函数型接口 有输入有返回
*/
Function<String,Integer> function = s ->{return s.length();};
System.out.println(function.apply("abc"));
/**
* 断定型接口 有输入有返回,返回值是bool型
*/
Predicate<String> predicate = s -> {return s.isEmpty();};
System.out.println(predicate.test("hello"));
/**
* 消费型接口 有输入 无返回
*/
Consumer<String> consumer = s ->{System.out.println(s);};
consumer.accept("this is consumer function");
/**
* 供给型接口 无输入 有返回
*/
Supplier<String> supplier = ()->{return "this is supplier function";};
System.out.println(supplier.get());
}
}
@AllArgsConstructor
@Data
@NoArgsConstructor
@Accessors(chain = true)
class Book{
private int id;
private String bookName;
private Double price;
int comparePrice(Double price1,Double price2){
if(price1 > price2){
return 1;
}else if(price1 < price2){
return -1;
}else {
return 0;
}
}
}
运行结果
Book(id=1, bookName=java, price=50.36)
[Book(id=1, bookName=java, price=50.36), Book(id=2, bookName=c++, price=60.68), Book(id=3, bookName=c primer, price=70.36), Book(id=4, bookName=Python, price=71.2)]
PYTHON
2
4
6
3
false
this is consumer function
this is supplier function
Process finished with exit code 0