集合中的常用转化

集合中的常用转化


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());
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值