集合中的常用转化
1.将 List< T > 提取其中某个字段转换成 List< T > :
例: 从 List< UserEntity > userList 提取 UserEntity 中的一个字段,如手机号 phoneNum:
(1).使用stream的方式:
List<String> phoneNumList = userList.stream().map(UserEntity -> UserEntity.getPhoneNum()).collect(Collectors.toList());
(2).使用guava:
List<String> phoneNumList = Lists.transform(userList,UserEntity -> UserEntity.getPhoneNum());
.
.
2.List 与 Set 的相关转化:
(1) 例:List< T > list 转化为 Set< T > set
Set< T > set = new HashSet(userList);
(2) 例:Set< T > set 转化为 List< T > list
List< T > list = new ArrayList(set);
.
.
3.集合取交集,并集,差集
(1) 取 list1 与 list2 的交集
List<String> newList = list1.stream().filter(item -> list2.contains(item)).collect(toList());
(2) 差集 (list1 - list2)
List<String> newList = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
(3) 并集 (list1 + list2 去重)
List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
listAll.addAll(listAll2);
List<String> newList = listAll.stream().distinct().collect(toList());
.
.
4.List < T > 转 Map< T , T >
详细版链接:List转Map
例1: List < Entity> 转 Map<Entity.getId,Entity>
Map<Long, VipEntity> vipMap = vipList.stream().collect(Collectors.toMap(VipEntity::getUserId, v -> v, (v1, v2) -> v1));
例2:List < Long> 转 Map<Long,Long>
Map<Long, Long> map = list.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));
.
.
5.Map< T , T > 转 List< T >
例:Map< Integer , String > 转 List< T >
(1) Map的key转List
List<Integer> result = map.keySet().stream().collect(Collectors.toList());
(2) Map的value转List
List<String> result = map.values().stream().collect(Collectors.toList());