List<String> listA = new Arraylist();
List<String> listB = new Arraylist();
Given above 2 lists, I want to iterate and call the same method on each element.
Option 1
for(String aStr: listA){
someCommonMethodToCall(aStr);
someCommonMethodToCall(aStr);
...
}
for(String bStr: listB){
someCommonMethodToCall(bStr);
someCommonMethodToCall(bStr);
...
}
or
Option 2
List<String> mergedList = new ArrayList();
mergedList.addAll(listA);
mergedList.addAll(listB);
for(String elem: mergedList){
someCommonMethodToCall(elem);
someCommonMethodToCall(elem);
...
}
or
Option 3
I feel the Option 1 should be the best. Is there some Java 8 lambda way to do this? Also, performance wise, would anything better than Option 1?
You can stream the lists and concat the streams into one:
Stream.concat(listA.stream(), listB.stream())
.forEach(elem -> {
someCommonMethodToCall(elem);
someOtherMethodToCall(elem);
});
With Java 8 you can use streams:
Stream.concat(listA.stream(), listB.stream())
.forEach(this::someCommonMethodToCall);
You can use the peek
method of a Stream
for the first method call followed by forEach
:
List<Integer> one = Arrays.asList(1, 2, 3);
List<Integer> two = Arrays.asList(4, 5, 6);
Stream.concat(one.stream(), two.stream())
.peek(System.out::print)
.forEach(System.out::println);
The following will also work using Eclipse Collections tap
method followed by forEach
:
List<Integer> one = Arrays.asList(1, 2, 3);
List<Integer> two = Arrays.asList(4, 5, 6);
LazyIterate.concatenate(one, two)
.tap(System.out::print)
.forEach(System.out::println);
You can chain as many method calls as you need using peek
or tap
but what I would recommend is extracting a composite method which makes both method calls.
Note: I am a committer for Eclipse Collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With