Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over 2 lists in java

Tags:

java

loops

java-8

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?

like image 512
Ankush Avatar asked Aug 28 '17 20:08

Ankush


3 Answers

You can stream the lists and concat the streams into one:

Stream.concat(listA.stream(), listB.stream())
    .forEach(elem -> {
        someCommonMethodToCall(elem);
        someOtherMethodToCall(elem);
    });
like image 132
shmosel Avatar answered Oct 21 '22 11:10

shmosel


With Java 8 you can use streams:

Stream.concat(listA.stream(), listB.stream())
        .forEach(this::someCommonMethodToCall);
like image 45
Costi Ciudatu Avatar answered Oct 21 '22 10:10

Costi Ciudatu


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.

like image 29
Donald Raab Avatar answered Oct 21 '22 10:10

Donald Raab