public static void main(String[] args) {
List<String> list1 = Arrays.asList("aaa", "bbb", "ccc");
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<Foo> list3 = Arrays.asList(new Foo(),new Foo(),new Foo());
for (int i=0;i<list1.size();i++) {
System.out.println(output(list1.get(i),list2.get(i),list3.get(i)));
}
}
private static String output(String first, Integer second, Foo third) {
return first + second + third;
}
public class Foo {
public int get(int i)
{
return i;
}
}
aaa1org.example.Foo@4aa298b7
bbb2org.example.Foo@7d4991ad
ccc3org.example.Foo@28d93b30
Stream test = IntStream.range(0,list1.size())
.Stream.concat(Stream.of(list1),Stream.of(list2),Stream.of(list3)).map(this::output).map(xxx::get)
.collect(Collectors.toList())
.forEach(System.out::println);
xxx
part and got stuck in here.map
in nested method call.public class Bar {
String list1;
Integer list2;
Foo list3;
Bar(String list1Con,Integer list2Con,Foo list3Con){
list1 = list1Con;
list2 = list2Con;
list3 = list3Con;
}
public Map<String,Object> get(int index) {
return new HashMap<String,Object>() {{
put("list1",list1);
put("list2",list2);
put("list3",list3);
}};
}
}
List<Bar> listBar = Arrays.asList(
new Bar("aaa",1,new Foo()),
new Bar("bbb",2,new Foo()),
new Bar("ccc",3,new Foo())
);
IntStream.range(0, listBar.size()).mapToObj(listBar::get).map(Bar::get).map(Map::values).forEach(System.out::println);
mapToObj
to apply in Bar::get
Frame challenge:
Your problem is not what streams are meant for.
The typical streams usage is: have some collection (or similar source), independently operate on every element of that collection, and return some result.
You don't have a single collection source, and you don't need a result, you just have a side effect (printing). And the power of streams (e.g. parallel execution) would probably break your expectation, that the side effects happen in order
Sry I'm new in using stream.
You can make it work if you find or write an adapter that creates a stream of triples (String/Integer/Foo) from your three lists, and then use stream functions to operate on that stream, but I'd recommend to not follow that path until you got some more experience with streams.
In general, I don't see benefit in transforming each and every loop into streams expressions. There are many situations where streams make your code more concise and better readable, but in your case, IMHO the loop is perfectly fine.
You have three lists of equal size, and the elements at identical indices belong together. Most of the time, this is a hint that the combination of these three things (String, Integer and Foo) has a domain meaning, and is worth a class of its own (let's call it MyCombination
, as of course I don't know what would be a proper name in your domain).
Then your three-lists problem vanishes, you only have a single List<MyCombination>
where you can easily apply streams functions.