Do you need performance? Here you go!
Using a for loop for each loop is optional.
int s = list.size(); for(int i = 0; i < s-1; i++){ for(int n = i+1; n< s;n++){ if(list.get(i).equals(list.get(n))){ System.out.println("Duplicate"); } } }
You will never compare a combination twice.
Also, to fully answer your question: foreach requires more resources and reduces performance
To achieve the same result using the foreach statement, you would create a large heap and slow down the application, and also more instructions are processed by the processor so that you not only lose memory, but also calculate performance. Also, try to avoid calling the size () method more than once, so your list will not be changed in this procedure. It also reduces CPU usage, but requires very little more RAM (int s).
Thus, your approach to "C" is almost optimal.
For convenience, I used java api calls, it should also be easy to use this example in your target structure.
EDIT: Improve performance even further by preserving the size of the list to reduce method calls.
source share