我想将for循环更改为main方法中包含的流。
这是我的主要方法
List<Model1> list = new ArrayList<>();
List<Model2> model = Stream.iterate(0, n -> n + 1).limit(10).map(m -> new Model2(m))
.collect(Collectors.toList());
List<Model2> model2 = Stream.iterate(11, n -> n + 1).limit(10).map(m -> new Model2(m))
.collect(Collectors.toList());
list.add(new Model1("a", model));
list.add(new Model1("b", model2));
List<Model3> list3=new ArrayList<>();
for(Model1 m:list) {
for(Model2 m2: m.getModel()) {
Model3 m3=new Model3();
m3.setStr(m.getS1());
m3.setValue(m2.getVal());
list3.add(m3);
}
}
list3.stream().forEach(s->
System.out.println(s.getStr()+"::"+s.getValue()));
以下是我的模特班
public class Model1 {
private String s1;
private List<Model2> model;
// getter setter
}
我的下一个模特
public class Model2 {
private Integer val;
//getter setter
}
我要在其中设置数据的模型
public class Model3 {
private String str;
private Integer value;
// getter setter
}
我的主要方法的输出将是:
a::0
a::1
a::2
a::3
a::4
a::5
a::6
a::7
a::8
a::9
b::11
我想要使用Java流的相同输出
您可以这样:
list.stream()
.flatMap(m->m.getModel().stream().map(m2->new Model3(m.getS1(),m2.getVal())))
.collect(Collectors.toList()); // or .collect(Collectors.toCollection(ArrayList::new))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句