For loop 使用Java8进行循环优化
如何用一条线实现这一点 我目前正在尝试这样做 例如:For loop 使用Java8进行循环优化,for-loop,foreach,java-8,For Loop,Foreach,Java 8,如何用一条线实现这一点 我目前正在尝试这样做 例如: {{"id" :"2", values: ["10","11", "12"]} , {"id" : "3", values : ["23"]}} 到 我的java代码是 Map<Integer, List<Integer>> attrMap = new HashMap<>(); //getAllData() & item.getValues() both returns List getAllD
{{"id" :"2", values: ["10","11", "12"]} , {"id" : "3", values : ["23"]}}
到
我的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());
});
});
Map attrMap=newhashmap();
//getAllData()和item.getValues()都返回列表
getAllData().forEach(项->{
item.getValues().forEach(val->{
attrMap.ComputeFabSent(item.getId(),(k)->
新建ArrayList<>()).add(val.getValue());
});
});
我怎么能只做一行呢?假设您有这样的输入:
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;
}
}
静态类数据{
私有最终int id;
私有最终列表值;
公共int getId(){
返回id;
}
公共列表getValues(){
返回值;
}
公共数据(int-id,列表值){
超级();
this.id=id;
这个值=值;
}
}
可以通过以下方式完成:
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]
List result=Arrays.asList(
新数据(2,数组。asList(10,11,12)),
新数据(3,数组.asList(23)))
.stream()
.flatMap(d->d.getValues().stream().map(x->new AbstractMap.SimpleEntry(d.getId(),x)))
.collect(Collectors.toList());
System.out.println(结果);//[2=10, 2=11, 2=12, 3=23]
我正在把这些收集到
Pair
或AbstractMap.SimpleEntry
由于ID是唯一的,您可以像
Map<Integer, List<Integer>> attrMap = getAllData().stream()
.collect(Collectors.toMap(
item -> item.getId(),
item -> item.getValues().stream().map(i->i.getValue()).collect(Collectors.toList())));
您刚刚通过删除换行符将
项
转换为结果映射的条目
和val
转换为列表的元素
?这个问题有点荒谬。首先,最重要的是真正的优化(时间+数据),行数只是为了可读性。当我看到某些代码不再更改时,有时我会删除换行符,以便更快地滚动代码。但仅此而已。我的意思是避免两个foreach循环&使用一个foreach循环。可能吗?是的,ID是唯一的。我不认为这比OP中的代码短很多。我的意思是避免两个foreach循环&使用一个foreach循环。可能吗?
Map<Integer, List<Integer>> attrMap = getAllData().stream()
.collect(Collectors.toMap(
item -> item.getId(),
item -> item.getValues().stream().map(i->i.getValue()).collect(Collectors.toList())));
{{"id" :"2", values: ["10","11", "12"]} , {"id" : "3", values : ["23"]}}