在 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
Collectors.toMap
。
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]
}
}