Java ArrayList Select N Items

Say I have an ArrayList containing the elements {1,2,3,4}, and I want to list all the possible combinations of two elements in an ArrayList. those. (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). What is the most elegant way to do this?

+5
source share
1 answer

Nested for loops will 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).
    }
}
+6
source

All Articles