java8 stream/optional个人测试demo记录

 

备忘记录

 

package cc.ash;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class StreamTest {

    public static void main(String[] args) {

        ArrayList<Stu> stus = new ArrayList<>();
        Stu a = new Stu("name-A", 17, 64, "A");
        Stu b = new Stu("name-B", 20, 58, "B");
        Stu c = new Stu("name-C", 27, 60, "C");
        Stu d = new Stu("name-D", 24, 56, "D");

        stus.add(a);
        stus.add(b);
        stus.add(c);
        stus.add(d);

//        streamOpt(stus);
        stus.add(null);
        optionalHandleClct(stus);
        optionalHandle(null);
    }


    public static void streamOpt(List<Stu> stuList) {

        stuList.stream()
                .filter(s -> s.getAge() > 19)
                .peek(o -> System.out.println(o.getName()))
                .sorted((x, y) -> x.getWeight() - y.getWeight())//.mapToInt(Stu::getWeight).sum();
                .peek(o -> System.out.println(o.getName()))
                .map(Stu::getAlias)
                .peek(System.out::println)
                .collect(Collectors.toList());

        stuList.stream()
                .filter(o -> o.getWeight() > 45 && o.getWeight() < 61)
//                .sorted((x, y) -> x.getWeight() - y.getWeight())
                //默认升序、反转降序。体重相同在根据年龄排序
                .sorted(Comparator.comparing(Stu::getWeight).reversed().thenComparing(Stu::getAge))
                .forEach(per -> System.out.println(per.getName()));

    }

    public static int optionalHandle(Stu stu) {
        return Optional.ofNullable(stu).map(Stu::getAge).orElse(-1);
//        return stu == null ? -1 : stu.getAge(); //等价
//        if(stu == null) {
//            System.out.println("无信息,日志输出,异常处理");
//            return  -1;
//        }
//        return stu.getAge();
    }
    public static void optionalHandleClct(List<Stu> stu) {

        int sum = stu.stream().mapToInt(o -> Optional.ofNullable(o).map(Stu::getAge).orElse(-1)).sum();
        System.out.println(sum);

    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
class Stu {
    private String name;
    private int age;
    private int weight;
    private String alias;
}
View Code

 

stream

https://blog.csdn.net/qq_20989105/article/details/81234175

lambda

https://www.jianshu.com/p/8d7f98116693

posted @ 2019-11-05 15:01  毁乐乖狂,自有诪张  阅读(222)  评论(0编辑  收藏  举报