Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
Ben Siver Avatar asked Oct 07 '11 04:10

Ben Siver


People also ask

How do you find the nth element of an ArrayList?

if i have 10 elements in a Arraylist how can i get 5th element? You can use get(index) method to access any element in arraylist. simply use get method.

How do you randomly select from an ArrayList?

nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.

How do you select an element in an ArrayList?

To get an element from ArrayList in Java, call get() method on this ArrayList. get() method takes index as an argument and returns the element present in the ArrayList at the index. E element = arraylist_1. get(index);


1 Answers

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).
    }
}
like image 180
Mark Byers Avatar answered Oct 17 '22 19:10

Mark Byers