public class test {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!");
}
};
r.run();
System.out.println("--------------------------------------");
Runnable r1 = () -> {
System.out.println("Hello Lambda");
};
r1.run();
}
}
语法格式2:有一个参数,并且无返回值,小括号可省略不写,:
public class test {
public static void main(String[] args) {
Consumer con = x -> {
System.out.println(x);
};
con.accept("QWERTY");
}
}
语法格式3:有2个以上的参数,有返回值,并且Lambda体中有多条返回值
public class test {
public static void main(String[] args) {
Comparator com = (x,y) -> {
System.out.println("函数式接口");
return Integer.compare(x,y);
};
}
}
语法格式4:若Lambda体中只有一条语句,return和大括号都可省略不写
public class test {
public static void main(String[] args) {
Comparator com = (x,y) -> Integer.compare(x,y);
}
}
@FunctionalInterface
public interface MyFun {
Integer getValue(Integer num);
}
测试类
public class test {
public static void main(String[] args) {
Integer result = operation(10,x ->{
return x * x;
});
System.out.println(result);
}
//operation方法,参数1为一Integer类型数据,参数2为一运算接口
public static Integer operation(Integer num, MyFun myFun){
return myFun.getValue(num);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private String name;
private int age;
private Double salary;
}
测试类
public class test {
public static void main(String[] args) {
List list = Arrays.asList(
new Employee("1号", 25, 5000.0),
new Employee("2号", 35, 3000.0),
new Employee("3号", 35, 2000.0),
new Employee("4号", 35, 8000.0),
new Employee("5号", 65, 1000.0)
);
Collections.sort(list,(e1,e2)->{
if (e1.getAge() == e2.getAge()){
return e1.getName().compareTo(e2.getName());
}else {
return -Integer.compare(e1.getAge(),e2.getAge());
}
});
Iterator iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
3. 函数式接口
四大核心函数式接口
Consumer:消费型接口
void accept(T t);
Supplier:供给型接口
T get();
Function(T,R):函数型接口
R apply(T t);
Predicate:断言型接口
boolean test(T t);
例子
Consumer:消费型接口
@Test
public void test(){
this.happy(1000,m -> {
System.out.println("我消费了"+ m);
});
}
public void happy(double money, Consumer con){
con.accept(money);
}
Supplier:供给型接口
@Test
public void test(){
List numList = this.getNumList(5, () -> (int) (Math.random() * 100));
for (Integer integer : numList) {
System.out.println(integer);
}
}
//产生指定数量的整数
public List getNumList(int num, Supplier sup){
List list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(sup.get());
}
return list;
}
Function(T,R):函数型接口
@Test
public void test(){
System.out.println(this.handler("str", str -> (str + "123")));
}
//处理字符串
public String handler(String str, Function fun){
return fun.apply(str);
}
Predicate:断言型接口
@Test
public void test(){
List stringList = Arrays.asList("qwe", "123", "hello", "ranhaifeng", "asdasdsaewqewqe");
List list = filterStr(stringList, s -> (s.length() > 3));
for (String s : list) {
System.out.println(s);
}
}
//将满足条件的字符串放入集合
public List filterStr(List list, Predicate pre){
List stringList = new ArrayList<>();
for (String s : list) {
if (pre.test(s)){
stringList.add(s);
}
}
return stringList;
}
@Test
public void test() {
List list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff");
list.stream().map(str -> str.toUpperCase(Locale.ROOT)).forEach(System.out::println);
}
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
public class test {
@Test
public void test() {
List list = Arrays.asList("aaa", "bbb");
list.stream().flatMap(test::filterCharacter).forEach(System.out::println);
}
public static Stream filterCharacter(String str){
List list = new ArrayList<>();
for (char c : str.toCharArray()) {
list.add(c);
}
return list.stream();
}
}
5.4 排序
public class test {
@Test
public void test(){
//自然排序
List list = Arrays.asList("aaa", "eee", "ddd", "bbb");
list.stream().sorted().forEach(System.out::println);
//定制排序
List list1 = Arrays.asList(
new Person("张三", 18, 2000.0),
new Person("李四", 18, 5000.0),
new Person("王五", 45, 8700.0),
new Person("赵六", 42, 4200.0),
new Person("陈七", 56, 13100.0)
);
list1.stream().sorted((p1,p2) -> {
if (p1.getAge().equals(p2.getAge())){
return p1.getSale().compareTo(p2.getSale());
}else {
return p1.getAge().compareTo(p2.getAge());
}
}).forEach(System.out::println);
}
}
5.5 查找与匹配
public class test {
@Test
public void test(){
List list = Arrays.asList(
new Person("张三", 18, 2000.0, Person.Status.BUSY),
new Person("李四", 18, 5000.0,Person.Status.FREE),
new Person("王五", 45, 8700.0,Person.Status.VOCATION),
new Person("赵六", 42, 4200.0,Person.Status.BUSY),
new Person("陈七", 56, 13100.0,Person.Status.BUSY)
);
//allMatch 检查是否匹配所有元素,返回值为Boolean类型
boolean b = list.stream().allMatch(e -> e.getStatus().equals(Person.Status.BUSY));
System.out.println(b); // false
//anyMatch 检查是否匹配至少一个元素,返回值为Boolean类型
boolean b1 = list.stream().anyMatch(e -> e.getStatus().equals(Person.Status.BUSY));
System.out.println(b1); // true
//noneMatch 检查是否没有匹配所有元素,返回值为Boolean类型
boolean b2 = list.stream().noneMatch(e -> e.getStatus().equals(Person.Status.BUSY));
System.out.println(b2); // false
//findFirst 返回第一个元素
//Optional 防止空指针异常的类型,如果first为null,可以使用.orelse()方法指定一个不为空的对象
Optional op1 = list.stream()
.sorted((e1, e2) -> Double.compare(e1.getSale(), e2.getSale())).findFirst();
System.out.println(op1.get()); // Person(name=张三, age=18, sale=2000.0, status=BUSY)
//findAny 返回当前流中的任意元素
//parallelStream 并行流,多个进程同时去进行filter、findAny,谁先找到算谁的
Optional op2 = list.parallelStream().filter(e -> e.getStatus().equals(Person.Status.FREE)).findAny();
System.out.println(op2.get()); // Person(name=李四, age=18, sale=5000.0, status=FREE)
//count 返回流中元素的总个数
long count = list.stream().count();
System.out.println(count); // 5
//max 返回流中的最大值
Optional max = list.stream().max((e1, e2) -> Double.compare(e1.getSale(), e2.getSale()));
System.out.println(max.get()); // Person(name=陈七, age=56, sale=13100.0, status=BUSY)
//min 返回流中的最小值
//返回list中的最小工资数
System.out.println(list.stream().map(Person::getSale).min(Double::compare).get()); // 2000.0
}
}
public class test {
@Test
public void test(){
List list = Arrays.asList(
new Person("张三", 18, 2000.0, Person.Status.BUSY),
new Person("李四", 18, 5000.0,Person.Status.FREE),
new Person("王五", 45, 8700.0,Person.Status.VOCATION),
new Person("赵六", 42, 4200.0,Person.Status.BUSY),
new Person("陈七", 56, 13100.0,Person.Status.BUSY)
);
List list1 = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//从0开始,0作为x,先取y=1,执行x+y=1,再将x作为1,y取流中下一个元素2,一直执行下去
Integer sum = list1.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum);
//上面那个返回值是Integer,是因为有起始值,不可能为空,而这条语句没有起始值,有可能为空!
Optional reduce = list.stream().map(Person::getSale).reduce(Double::sum);
System.out.println(reduce.get());
}
}
public class ForkJoinCalculate extends RecursiveTask {
private static final long serialVersionUID = 12313435L;
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();
}
}
}
测试:
public class test {
@Test
public void qwe(){
Instant start = Instant.now();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinCalculate forkJoinCalculate = new ForkJoinCalculate(0, 10000000000L);
Long sum = forkJoinPool.invoke(forkJoinCalculate);
System.out.println(sum);
Instant end = Instant.now();
System.out.println("消耗时间:" + Duration.between(start,end).toMillis()); //5701
}
//普通for循环计算
@Test
public void test2(){
Instant start = Instant.now();
long sum = 0L;
for (int i = 0; i < 10000000000L; i++) {
sum += i;
}
System.out.println(sum);
Instant end = Instant.now();
System.out.println("消耗时间:" + Duration.between(start,end).toMillis()); //没跑出来
}
//java8并行流
@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()); //2145
}
}
还是java8并行流快!
5.8 Optional容器
这里只介绍基本的API,应用举例不展开,有兴趣的请查阅其它资料
public class test {
@Test
public void test(){
// Option.of(T t):创建一个Optional实例
Optional op = Optional.of(new Person());
Person person = op.get();
System.out.println(person); // Person(name=null, age=null, sale=null, status=null)
}
@Test
public void test2(){
// Option.empty():创建一个Optional实例
Optional op = Optional.empty();
System.out.println(op.get()); // java.util.NoSuchElementException: No value present
}
@Test
public void test3(){
// Option.ofNullable(T t):若t不为null,创建Optional实例,否则创建空实例
Optional op = Optional.ofNullable(new Person());
System.out.println(op.get()); // Person(name=null, age=null, sale=null, status=null)
}
@Test
public void test4(){
Optional op = Optional.ofNullable(new Person());
// Option.isPresent():判断是否包含值
if (op.isPresent()){
System.out.println(op.get()); // Person(name=null, age=null, sale=null, status=null)
}
}
@Test
public void test5(){
Optional op = Optional.ofNullable(null);
// Option.orElse(T t):如果调用对象包含值,返回该值,否则返回t
Person emp = op.orElse(new Person("qwe", 18, 2000.2, Person.Status.BUSY));
System.out.println(emp); // Person(name=qwe, age=18, sale=2000.2, status=BUSY)
}
@Test
public void test6(){
Optional op = Optional.ofNullable(null);
//如果调用对象包含值,返回该值,否则返回s获取的值
Person person = op.orElseGet(() -> new Person());
System.out.println(person); // Person(name=null, age=null, sale=null, status=null)
}
@Test
public void test7(){
Optional op = Optional.ofNullable(new Person("qwe", 18, 200.0, Person.Status.BUSY));
// map(Function f):如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty()
Optional str = op.map(e -> e.getName());
System.out.println(str.get()); // qwe
// faltMap(Function mapper):map类似,要求返回值必须是Optional,方法中必须用Optional包装
Optional str2 = op.flatMap(e -> Optional.of(e.getName()));
System.out.println(str2.get());
}
}
评论列表(0条)