Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to iterate over two related ArrayLists?

I am looking for a clean and simple way to iterate over two ArrayLists that are related directly in that each index of one maps to the index of another (in relationship).

Currently, I'm doing it via a simple for loop and I tried looking into lambdas and for-each loops but don't see a way to apply it to two lists at the same time that are of the same size.

firstList: ["Blue", "Red", "Green"]

secondList: ["Sky", "Roses", "Grass"]

for(int i = 0; i < firstList.size(); i++){
    System.out.println(firstList.get(i) + " " + secondList.get(i));
}

Result:

Blue Sky
Red Roses
Green Grass

Is there a way to effectively iterate over both lists simultaneously using a lambda or a for-each loop to avoid using a for loop?

like image 451
Jack Avante Avatar asked Dec 10 '22 23:12

Jack Avante


2 Answers

What you have it is already pretty efficient (assuming that you are using ArrayList), concise and readable. However, this type of scenarios:

I am looking for a clean and simple way to iterate over two ArrayLists that are related directly in that each index of one maps to the index of another (in relationship).

typically require a class that defines the relationship, in your case:

public class MyC {
    private final String color;
    private final String object;

    public MyC(String color, String object) {
        this.color = color;
        this.object = object;
    }
    public String getColor(){
        return color;
    }
    public String getObject(){
        return object;
    }

    @Override
    public String toString() {
        return "MyC{" +
                "color='" + color + '\'' +
                ", object='" + object + '\'' +
                '}';
    }
} 

then the two lists would become one:

List<MyC> list = List.of(new MyC("Blue", "Sky"), new MyC("Red", "Roses"), new MyC("Green", "Grass") );

and then you can use:

list.forEach(System.out::println);
like image 95
dreamcrash Avatar answered Jan 12 '23 00:01

dreamcrash


The Answer by dreamcrash is correct: While your looping of a pair of arrays works, you should instead take advantage of Java as a OOP language by defining your own class.

Record

Defining such a class is even simpler in Java 16 with the new records feature. Write your class as a record when it’s main purpose is communicating data, transparently and immutably.

A record is very brief by default. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString. You need only declare the type and name of each member field.

record ColorNoun ( String color , String noun ) {}

Use a record like a conventional class. Instantiate with new.

ColorNoun blueSky = new ColorNoun ( "Blue" , "Sky" ) ;

Note that a record can be declared locally within a method, or declared separately like a conventional class.

like image 45
Basil Bourque Avatar answered Jan 11 '23 23:01

Basil Bourque