空指针异常终结者:optional

package optional;



import java.util.*;

public class Test {
    public static void main(String[] args) {
        List stdudents = new ArrayList();
        Student student = new Student("liyu",70);
        Student student1 = new Student("liyu",80);
        stdudents.add(student);
        stdudents.add(student1);

       Optional score= stdudents.stream()
                .map(Student::getScore)
                .filter(s-> s<60)
                .reduce((a,b)->a+b);


        System.out.println(score.orElse(0));


        Map map= new HashMap();
        map.put(1001,"篮球");
        map.put(1002,"足球");
        map.put(1003,"羽毛球");

        //获取key为1005的value
        System.out.println("a="+map.get(1005));
        Map map1= new HashMap();
        map1.put(1005,"篮球");

        //获取key为1005的value
        String a2= Optional.ofNullable(map.get(1005)).orElse("无");
        System.out.println("a2="+a2.toString());
        
        //如果Optional.ofNullable(map)里的map不为null,返回的结果为他本身,否则为map1
        Map a1= Optional.ofNullable(map).orElse(map1);
        System.out.println("a1="+a1.toString());

    }
}

 

你可能感兴趣的:(java基础)