javaarraylist

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?


Solution

  • 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))    
      }
    }