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()));