Basic
Basic

Reputation: 26766

Get unique pairs of elements from an ArrayList in Java

I've got an ArrayList which contains a series of integers (represnting indices in another ArrayList).

I need to extract each Unique pair eg...

ArrayList = 1,4,5,7

I need:

1:4
1:5
1:7
4:5
4:7
5:7

What's the simplest method of achieving this?

Upvotes: 4

Views: 5723

Answers (5)

GEORGE
GEORGE

Reputation: 1

To answer your question based on the example given: You do not need to convert to Set or List:

 for (int i = 0; i < input.length; i++) {
        for (int j = i + 1; j < input.length; j++) {
                System.out.println(input[i] + "," + input[j]);
        }
    }

Sample: -> int[] input = {1,4,5,7};

Output:

1,4
1,5
1,7
4,5
4,7
5,7

Upvotes: 0

ssedano
ssedano

Reputation: 8432

I wonder if using a graph structure with unidirectional relation would suit this problem.

It is way much work than a simple permutation, but probably more interesting to implement. Specially for a large number of pairs.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240948

convert list to Set and back to List for unique filtering

for(int i = 0 ; i < list.size(); i ++){
  for(int j = i+1 ; j < list.size(); j ++){
    System.out.println(list.get(i) + "," + .list.get(j))    
  }
}

Upvotes: 7

Attila
Attila

Reputation: 28772

You could have two indices: one for the first part, the other for the second. Then interate through with the first form the beginning to the one-but-last element, and in an inner loop iterate through with the second from one-past-the first to the end.

Upvotes: 0

tskuzzy
tskuzzy

Reputation: 36476

Well loop through all possible choices for the first element. For each of those, loop through all possible choices for the second.

I'll leave the finding duplicates part up to you (hint: use a Set).

Upvotes: 0

Related Questions