In fact, there is a little perplexity. A HashSet or any Set not about order, if a TreeSet that is ordered based on a Comparator .
At the moment, under java-8, when you put elements in a HashSet (and do not change it) - there will be an order of how the elements will be laid out; but again, provided that you do not add or remove any of them. This can change at any given time, so do not rely on it.
For example, follow these steps:
String[] colors = new String[] { "red", "green", "blue", "orange" }; List<String> colorsList = Arrays.asList(colors); HashSet<String> colorsSet = new HashSet<>(); colorsSet.addAll(colorsList); System.out.println(colorsSet);
How many times in java-8 at the moment you always get the same result:
[red, orange, green, blue]
But as soon as you do the internal shuffling:
for (int i = 0; i < 1000; ++i) { colorsSet.add("" + i); } for (int i = 0; i < 1000; ++i) { colorsSet.remove("" + i); } System.out.println(colorsSet);
You can see that the output changes because Set is out of order. The key point is that there is no order, the fact that you see the order is not a guarantee that it will occur every time - there may be an assembly in java-8 that will violate this order. And in fact, this is easy to observe using java-9 , for example - where is the randomization pattern for the new Set s.
If you run this several times, the result will be different:
Set<String> set = Set.of("red", "green", "blue", "orange"); System.out.println(set);
Thus, it is obvious that you stream from such a Set , the order will not be guaranteed, and therefore, you really will see different results from launch to launch.