集合之间的互转
确认JDK是否支持如下集合的转换
Collectors
Objects
参考:
List< T>转Map<String, T>
PHP:
Map<String, T> array_combine(() -> T::getXXX, List<T> list);
Java:
private static <T, R> Map<R, T> arrayCombine(Function<T, R> mapper, List<T> list) {
Map<R, T> map = new HashMap<>(list.size());
for (T t : list) {
map.put(mapper.apply(t), t);
}
return map;
}
List<User> userList = new ArrayList<>(2);
User user1 = new User(23, "user1");
User user2 = new User(45, "user2");
userList.add(user1);
userList.add(user2);
Map<String, User> stringUserMap = arrayCombine(User::getName, userList);
List< T>转Map<String, List< T>>
统计某个 key 的集合。
PHP:
Java:
private static <T, R> Map<R, List<T>> countList(Function<T, R> function, List<T> list) {
Map<R, List<T>> map = new LinkedMap<>();
for (T t : list) {
R apply = function.apply(t);
List<T> tList = map.get(apply);
if (null == map.get(apply)) {
tList = new LinkedList<>();
map.put(apply, tList);
}
tList.add(t);
}
return map;
}
List< T>转List< String>
PHP:
List<String> array_column(List<T> list, T::getXXX);
类似 array_cloumn,获取集合对象中的某个属性的集合。
private static <T, R> List<R> arrayColumn(Function<T, R> function, List<T> list) {
return list.stream().map(function).collect(Collectors.toList());
}
包装类型和集合互转
// 包装数据类型转集合
Integer[] integers = new Integer[]{1, 2};
List<Integer> integerList = Arrays.stream(integers).collect(Collectors.toList());
assertEquals(2, integerList.size());
assertEquals(1, (int) integerList.get(0));
assertEquals(2, (int) integerList.get(1));
// 基本数据类型数组转集合
int[] ints = new int[]{1, 2, 3};
List<Integer> integerList1 = Arrays.stream(ints).boxed().collect(Collectors.toList());
assertEquals(3, integerList1.size());
assertEquals(1, (int) integerList1.get(0));
assertEquals(3, (int) integerList1.get(2));
标签:map,Java,Map,List,list,互转,集合,new
From: https://www.cnblogs.com/okbuok/p/17433115.html