# Java 8 new features use

Use of new features in Java 8

Optional class

  • The Optional class is a container object that can be null. If the value exists, the isPresent() method will return true, and calling the get() method will return the object.

  • Optional is a container: it can hold values ​​of type T, or just null. Optional provides many useful methods so that we don't need to explicitly check for null values.

  • The introduction of the Optional class is a good solution to the null pointer exception.

Optional source code
public final class Optional<T> {
    
    

    // 这个是通用的代表NULL值的Optional实例
    private static final Optional<?> EMPTY = new Optional<>();

    // 泛型类型的对象实例
    private final T value;
    
    // 实例化Optional,注意是私有修饰符,value置为NULL
    private Optional() {
    
    
        this.value = null;
    }
    
    // 直接返回内部的EMPTY实例
    public static<T> Optional<T> empty() {
    
    
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }
    
    // 通过value实例化Optional,如果value为NULL则抛出NPE
    private Optional(T value) {
    
    
        this.value = Objects.requireNonNull(value);
    }
    
    // 通过value实例化Optional,如果value为NULL则抛出NPE,实际上就是使用Optional(T value)
    public static <T> Optional<T> of(T value) {
    
    
        return new Optional<>(value);
    }

    // 如果value为NULL则返回EMPTY实例,否则调用Optional#of(value)
    public static <T> Optional<T> ofNullable(T value) {
    
    
        return value == null ? empty() : of(value);
    }
   
}
Create an empty Optional
Optional<User> emptyOpt = Optional.empty();
emptyOpt.get();
Create a valued Optional
Optional<User> emptyOpt = Optional.of(user);
User user1 = emptyOpt.get();
logger.info(JSONObject.toJSONString(user1));
Null value judgment
// name不为空 否则orelse
String testname = Optional.ofNullable(user.getName()).orElse("李四");
logger.info(testname);
orElseGet assignment object
User user1 = new User(1, "张三", "西安");
User user2 = new User(2, "李四", "新疆");

user1 = null;
User user = Optional.ofNullable(user1).orElseGet(() -> user2);
logger.info(user.toString());
orElseThrow throws a null pointer
User user = new User(1, "张三", "西安");
user =null;
User result = Optional.ofNullable(user).orElseThrow(() -> new IllegalArgumentException());
map chain operation
User user = new User(1, "zhangSan_LISI", "西安");
String names = Optional.of(user)
    .map(u -> u.getName())
    .map(name -> name.toLowerCase())
    .map(str -> str.replace("_", ""))
    .orElseThrow(() -> new NullPointerException("空指针异常"));
logger.info(names);

Stream

In Java 8, the collection interface has two methods to generate streams:

  • stream() − Create a serial stream for the collection.
  • parallelStream() − Create a parallel stream for the collection.
Foreach
List<String> list = Arrays.asList("zhangsan", "", "lisi");
list.stream().forEach(System.out::println);
Map and Filter (mapping and filtering operations)
List<String> collect = list.stream()
    .filter(x -> "lisi".equals(x))
    .map(x ->x.toUpperCase())
    .collect(Collectors.toList());
collect.stream().forEach(System.out::println);
Sorted
Random random = new Random();
        random.ints().limit(20).sorted().forEach(System.out::println);
parallelStream parallel stream operation
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Lambda expression

  • Lambada allows a function to be used as a method parameter. Using Lambada can make the code concise.
Traverse the List collection

1. Use Lambada expressions similar to forEach

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
//froEace循环
for (Integer ret : list) {
    
    
	System.out.println(ret);
}

//使用Lambada表达式输出
list.stream().forEach(x -> System.out.println(x));
list.stream().filter(x -> x % 2 == 0).forEach(x -> System.out.println(x));

2. Operation Map

@Test
 public void test1() {
    
    
     List<HashMap<String, String>> list = new ArrayList<>();
     for (int i = 0; i < 10; i++) {
    
    
         HashMap<String, String> map = new HashMap<>();
         map.put(String.valueOf("键" + i), String.valueOf(i));
         list.add(map);
     }
     //遍历HashMap得到其中的键
     list.stream().forEach(x -> {
    
    
         for (String y : x.keySet()) {
    
    
             System.out.println("输出的值为:" + y);
         }
     });
     //遍历HashMap得到其中的值
     list.stream().forEach(x -> {
    
    
         for (Map.Entry y : x.entrySet()) {
    
    
             System.out.println("map中的值为:" + y);
         }
     });
 }
Traverse the Map
map.forEach((k, v) -> {
    
    
     System.out.println(k + "====" + v);
});
Create thread
public static void main(String[] args) {
    
    
       new Thread(() -> {
    
    
           System.out.println("我是进程1");
       }).start();
       new Thread(() -> {
    
    
           System.out.println("我是进程2");
       }).start();
       new Thread(() -> {
    
    
           System.out.println("我是进程3");
       }).start();
}
List to Map
@Test
public void test3() {
    
    
    List<Person> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
    
    
        Person person = new Person("Person" + i, String.valueOf(i));
        list.add(person);
    }
    Map<String, String> collect = list.stream().collect(Collectors.toMap(Person::getKey, Person::getValue));
    System.out.println(collect);
}
Map to List
@Test
public void test2() {
    
    
   HashMap<String, String> map = new HashMap<>();
   for (int i = 0; i < 10; i++) {
    
    
       map.put(String.valueOf("键" + i), String.valueOf(i));
   }
   System.out.println(map);
   //Map转List
   List<Person> collect = map.entrySet()
           .stream()
           .map(x -> new Person(x.getKey(), x.getValue()))
           .collect(Collectors.toList());
   for (Person x : collect) {
    
    
       System.out.println(x.getKey() + "====" + x.getValue());
   }
   map.forEach((k, v) -> {
    
    
       System.out.println(k + "====" + v);
   });
}
Map filtering
@Test
public void test6(){
    
    
    Map<String,String> map=new HashMap();
    map.put("1","3");
    map.put("1","1");
    map.put("3","4");
    map.put("4","6");

    Map<String, String> collect = map.entrySet().stream().filter(x -> String.valueOf(x.getKey()).equals("1")).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
    System.out.println(collect);
}

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/114176799