Ben Siver
Ben Siver

Reputation: 2948

Java ArrayList Choose N elements

Say I have an ArrayList containing the elements {1,2,3,4}, and I want to enumerate all possible combinations of two elements in the ArrayList. i.e. (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). What is the most elegant way of going about doing this?

Upvotes: 5

Views: 1173

Answers (1)

Mark Byers
Mark Byers

Reputation: 837966

Nested for loops would work:

for (int i = 0; i < arrayList.size(); ++i) {
    for (int j = i + 1; j < arrayList.size(); ++j) {
        // Use arrayList.get(i) and arrayList.get(j).
    }
}

Upvotes: 6

Related Questions