Java8 list转map,list转list

public class ListToListOrMapUtils {
    public static List list2list(List list, String fieldName4Key,Class<?> c) {
        /**
         *@param
         * list:输入list
         * fieldName4Key:字段名
         * c:类
         */
        List<Object> objectArrayList = new ArrayList<>();
        if (list != null) {
            try {
                PropertyDescriptor propDesc = new PropertyDescriptor(fieldName4Key, c);
                Method methodGetKey = propDesc.getReadMethod();
                for (int i = 0; i < list.size(); i++) {
                    Object o = list.get(i);
                    Object invoke = methodGetKey.invoke(o);
                    if(null != invoke){
                        objectArrayList.add(invoke);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new IllegalArgumentException("field can't match the key!");
            }
        }
        return objectArrayList;
    }

    public static  <K, V> Map<K, V> list2Map(List<V> list, String fieldName4Key,Class<V> c) {
        Map<K, V> map = new HashMap<K, V>();
        if (list != null) {
            try {
                PropertyDescriptor propDesc = new PropertyDescriptor(fieldName4Key, c);
                Method methodGetKey = propDesc.getReadMethod();
                for (int i = 0; i < list.size(); i++) {
                    V value = list.get(i);
                    @SuppressWarnings("unchecked")
                    K key = (K) methodGetKey.invoke(value);
                    map.put(key, value);
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("field can't match the key!");
            }
        }
        return map;
    }

用法如下:

Map<Object, User> userMap = ListToListOrMapUtils.list2Map(userList, "id", User.class);
List uidList = ListToListOrMapUtils.list2list(userList, "uid", User.class);

lambda 表达式实现


list转map:
List<Student> students= new ArrayList<>();
Map<Long, Student> mapOfStudent = students.stream().collect(Collectors.toMap(s -> s.getTaskCode(), s -> s,(v1,v2)->v1);

list转set:
List<Student> students= new ArrayList<>();
Set<String> sdfSet = students.stream()
                        .map(students::getStudentCode)
                        .collect(Collectors.toSet());
listתlist:
List<Student> students= students.stream().filter((Student student) ->
                studentIds.contains(student.getId())).collect(Collectors.toList());
分组
 Map<Long, List<ObjectRuleRef>> collect = objectRuleRefs.stream().collect(Collectors.groupingBy(item -> item.getObjectId()));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值