一、List转List
List<String> userIdList = userList.stream()
.map(User::getUserId).collect(Collectors.toList());
List<user> list = userList.stream()
.distinct().collect(Collectors.toList());
- 筛选出满足条件的用户(例如:筛选出姓陈,名字长度为3的名字成为新的List),startsWith() 方法用于检测字符串是否以指定的前缀开始。
List<String> list = nameList.stream()
.filter((String name) -> name.startsWith("陈")).filter((String name) -> name.length() == 3)
.collect(Collectors.toList());
List<A> aList = bList.stream()
.map(todo -> new A(todo.getName(), todo.getId(), todo.getAddress(), todo.getAge(), todo.getBirthday()))
.collect(Collectors.toList());
二、List转Map
Map<String, User> map = list.stream()
.collect(Collectors
.toMap(User::getUserName, a -> a, (key1, key2) -> key1));
//(key1,key2)->key1 表示如果出现某两个值属于同一个键时,使用哪一个值,
//示例中表示当出现这种情况时使用前面的值,如果为key2就使用后面的值。
Map<String, String> map = list.stream()
.collect(Collectors
.toMap(User::getUserId, User::getUserName, (key1, key2) -> key1));
Map<String, List<User>> map = list.stream()
.collect(Collectors.groupingBy(User::getUserName));
Map<Long, String> userMap = userList.stream()
.filter(map -> map.getUserName() != null)
.collect(Collectors
.toMap(Company::getUserId, Company::getUserName, (key1, key2) -> key2));
- 没有指定的key,value,key和value均使用拼接的方式
Map<String, String> map = list.stream().collect(Collectors.toMap(
k ->k.getName() + k.getDepartmentName,
v ->v.getCompanyName() + ";" + v.getLeaderName,
(oldValue, newValue) -> newValue));
三、List转Map
- 将Map<String,Integer>类型的值转为List
List<Integer> list = map.values().stream().collect(Collectors.toList());
// Java8 Stream
List<KeyValue> list = map.entrySet().stream().map(c -> new KeyValue(c.getKey(), c.getValue())).collect(Collectors.toList());