How to effectively get all pairs of elements?

Given the Set object, I want to go through all of its (unordered) pairs.

Example: Set = {1, 2, 3}, pairs: (1, 2), (1, 3), (2, 3).

When working with Vector<Integer> this can be achieved using the index of each element:

 for (int i = 0; i < vector.size(); i++) for (int j = i + 1; j < vector.size(); j++) // Do something with vector.get(i) and vector.get(j) 

But the elements in Set<Integer> have no indexes.

The best solution I've found so far is to convert Set to Vector and use the above solution.

Is there a more efficient / direct solution?

+8
java set pair
source share
2 answers
 List<Integer> list = new ArrayList<Integer>(mySet); for (int i = 0; i < list .size(); i++) for (int j = i + 1; j < list .size(); j++) // Do something with vector.get(i) and vector.get(j) 
+9
source share

In terms of complexity for this algorithm = n (n -1) / 2 , so O (n ^ 2) is the best you can get (sequential).

Although, if your set is really large, a set that is suitable only in RAM. You can optimize the algorithm by calculating the pair in a block way, similar to what is done when multiplying the matrix using tile blocks. This way you can reduce the% miss in cache and therefore increase overall performance.

In addition, you can introduce parallelization and split the work between threads / processes, as the algorithm looks awkwardly parallel.

+1
source share

All Articles