Java集合互转,集合转换

发布时间 2023-05-25 22:05:04作者: 沙里

集合之间的互转

确认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());
}