Created
January 10, 2020 03:39
-
-
Save upangka/b47a2a814e2b41c159459cd005670aa4 to your computer and use it in GitHub Desktop.
Optional为List<Object>的情况
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.caucoder.optional; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.Optional; | |
import java.util.stream.Collectors; | |
public class User { | |
public User(Integer id) { | |
this.id = id; | |
} | |
private Integer id; | |
public Integer getId() { | |
return id; | |
} | |
public void setId(Integer id) { | |
this.id = id; | |
} | |
public static void main(String[] args) { | |
List<User> list = new ArrayList<>(); | |
list.add(new User(3)); | |
list.add(new User(5)); | |
Optional<List<User>> optionalA = Optional.ofNullable(list); | |
getIdList(optionalA).stream().forEach(System.out::println); | |
list = null; | |
Optional<List<User>> optionalB = Optional.ofNullable(list); | |
getIdList(optionalB).stream().forEach(System.out::println); | |
} | |
/** | |
* 3 | |
* 5 | |
* List<User>为null时 | |
* | |
*/ | |
public static List<Integer> getIdList(Optional<List<User>> optional){ | |
return optional.orElseGet(()->{ | |
System.out.println("List<User>为null时"); | |
return Collections.emptyList(); | |
}).stream().map(item->{ | |
return item.getId(); | |
}).collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment