[英]Grouping elements from arrays by index into List<Map<String,Object>>
I have a Map<String, Object[]> in which key is the Array's name Object identifier aka collection name and its corresponding array of Objects.我有一个 Map<String, Object[]> ,其中键是数组的名称 Object 标识符又名集合名称及其对应的对象数组。
The objective is to be able to Merge the different entries of the Object [] into a List<Map<String,Object>> where the keys of each Map corresponds to the known Collection name and the Object is the iTh value of each array.目标是能够将 Object [] 的不同条目合并到一个 List<Map<String,Object>> 中,其中每个 Map 的键对应于已知的集合名称,并且每个数组的 Z497031794414A552435F901 的值是
In order to clarify this more:为了更清楚地说明这一点:
Lets say we have a Map<String, Object[]> with the following arrays.假设我们有一个带有以下 arrays 的 Map<String, Object[]>。
Map<String, Object[]> map = new HasMap<>();
Object[] ints = Stream.of(1,2,3,4,5).toArray();
Object[] dobules = Stream.of(1.0,2.0,3.0,4.0,5.0).toArray();
Object[] strings = Stream.of("a","b","c","d","e").toArray();
map.put("ints", ints);
map.put("doubles", dobules);
map.put("strings", strings);
Then the output of this entry should be like this:那么这个条目的output应该是这样的:
List<Map<String,Object>> where for the example up the List of maps would be like this List<Map<String,Object>> 例如,地图列表如下所示
{"ints": 1, "doubles":1.0, "strings":"a"},
{"ints": 2, "doubles":2.0, "strings":"b"},
{"ints": 3, "doubles":3.0, "strings":"c"},
{"ints": 4, "doubles":4.0, "strings":"d"},
{"ints": 5, "doubles":5.0, "strings":"e"}
I am looking specially a solution using java Collection streams Thank you so much我正在寻找使用 java 收集流的解决方案,非常感谢
Plain old approach:普通的旧方法:
List<Map<String, Object>> result = new ArrayList<>();
if(!map.isEmpty())
// Assume all the array lengths are the same
int length = map.values().iterator().next().length;
for(int i = 0; i < length; i++) {
Map<String, Object> row = new HashMap<>();
for(Map.Entry<String, Object[]> entry : map.entrySet()) {
row.put(entry.getKey(), entry.getValue()[i];
}
result.add(row);
}
}
Mixed approach:混合方法:
int length = map.values().iterator().next().length;
for(int i = 0; i < length; i++) {
final int index = i; // make compiler happy
result.add(map.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> e.getValue()[index])));
}
Pure functional approach:纯函数式方法:
int length = map.isEmpty() ? 0 : map.values().iterator().next().length;
List<Map<String, Object>> result =
IntStream.range(0, length)
.boxed()
.map(i -> map.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> e.getValue()[i])))
.collect(toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.