将 Java List<POJO> 转换为 Map<String, List<Object>>,其中键是字段名称,值是按字段列出的值列表

问题描述 投票:0回答:1

在 Java 中将

List<POJO>
转换为
Map<String, List<Object>>
,其中键是字段名称,值是字段值的列表。

class Train {
    public final String source;
    public final String destination;
    public final double cost;

    public Train(String source, String destination, double cost) {
        this.source = source;
        this.destination = destination;
        this.cost = cost;
    }
}

例如:

List<Train> trains = Arrays.asList(
    new Train("A", "B", 10.0),
    new Train("C", "D", 20.0),
    new Train("E", "F", 30.0)
);

应转换为:

Map<String, List<Object>> = ...  // {source=[A, C, E], destination=[B, D, F], cost=[10.0, 20.0, 30.0]}

注意:这不是 Java 8 List into Map 的重复,因为它没有确切说明如何转换数据,而仅意味着使用

Collectors.toMap

java reflection java-8 java-stream
1个回答
0
投票
class Main {
    public static void main(String[] args) {
        List<Train> trains = Arrays.asList(
                new Train("A", "B", 10.0),
                new Train("C", "D", 20.0),
                new Train("E", "F", 30.0)
        );
        Map<String, List<?>> map = Arrays.stream(Train.class.getFields())
                .collect(Collectors.toMap(Field::getName, f -> trains.stream()
                        .map(x -> {
                            try {
                                return f.get(x);
                            } catch (IllegalAccessException e) {
                                throw new IllegalStateException(e);
                            }
                        }).collect(Collectors.toList())));
        System.out.println(map.get("source"));          // [A, C, E]
        System.out.println(map.get("destination"));     // [B, D, F]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.