如何用一行代码实现这一点呢?
我目前正在尝试这样做
示例:
{{"id" :"2", values: ["10","11", "12"]} , {"id" : "3", values : ["23"]}}至
{{"id" :"2","value": "10"},{"id": "2","value":"11"},
{"id" :"3","value":"23"} , {"id" : "2", "value":"12"}}我的java代码是
Map<Integer, List<Integer>> attrMap = new HashMap<>();
//getAllData() & item.getValues() both returns List
getAllData().forEach(item - > {
item.getValues().forEach(val - > {
attrMap.computeIfAbsent(item.getId(), (k) - >
new ArrayList < > ()).add(val.getValue());
});
});我怎么能只做一行呢?
发布于 2017-07-14 18:08:40
因为it是唯一的,所以您可以这样做
Map<Integer, List<Integer>> attrMap = getAllData().stream()
.collect(Collectors.toMap(
item -> item.getId(),
item -> item.getValues().stream().map(i->i.getValue()).collect(Collectors.toList())));但是,当然,这仍然具有两个嵌套循环的性能特征。它将支持并行处理,但我怀疑您的数据是否足够大,以便从并行处理中获益。
此外,请注意,生成的map在结构上仍与您的第一个模式匹配,
{{"id“:"2",取值:"10","11","12"},{"id”:"3",取值:"23"}}
您刚刚将item转换为结果Map的条目,将val转换为List<Integer>的元素。
发布于 2017-07-14 17:04:16
假设您的输入如下所示:
static class Data {
private final int id;
private final List<Integer> values;
public int getId() {
return id;
}
public List<Integer> getValues() {
return values;
}
public Data(int id, List<Integer> values) {
super();
this.id = id;
this.values = values;
}
}可以通过以下方式完成:
List<SimpleEntry<Integer, Integer>> result = Arrays.asList(
new Data(2, Arrays.asList(10, 11, 12)),
new Data(3, Arrays.asList(23)))
.stream()
.flatMap(d -> d.getValues().stream().map(x -> new AbstractMap.SimpleEntry<>(d.getId(), x)))
.collect(Collectors.toList());
System.out.println(result); // [2=10, 2=11, 2=12, 3=23]我要把它们收集到Pair或AbstractMap.SimpleEntry上。
https://stackoverflow.com/questions/45098661
复制相似问题