Java – understand the order of elements in the stream generated from the HashSet
I read this official JAVA 8 document:
Try to understand the above behavior through this code
public class StreamOrderValidator { public static void main( String[] args ) { 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); // [red,orange,green,blue] List<String> processedColoRSSet = processStream(coloRSSet.stream()); System.out.println(processedColoRSSet); // [RED,ORANGE,GREEN,BLUE] } private static List<String> processStream(Stream<String> colorStream) { List<String> processedColorsList = colorStream.filter(s->s.length()<=6). map(String::toUpperCase).collect(Collectors.toList()); return processedColorsList; } }
I run this code many times, and the order of elements in the result stream is always the same (displayed as comments) I can't figure out how this proves the above quoted text about "commands are not kept as unordered sets"
I absolutely misunderstood the extracted text from JavaDocs
Solution
There are indeed some misunderstandings HashSet or any set is not about order, unless it is based on TreeSet sorted by comparator
At present, under java-8, once you put elements into a HashSet (and don't change it), there will be an order of how to layout elements; But again, if you don't add or delete any one This can change at any time, so don't rely on it
For example, run this:
String[] colors = new String[] { "red","orange" }; List<String> colorsList = Arrays.asList(colors); HashSet<String> coloRSSet = new HashSet<>(); coloRSSet.addAll(colorsList); System.out.println(coloRSSet);
No matter how many times you use java-8, you will always get the same output:
[red,blue]
But once you do some internal reshuffle:
for (int i = 0; i < 1000; ++i) { coloRSSet.add("" + i); } for (int i = 0; i < 1000; ++i) { coloRSSet.remove("" + i); } System.out.println(coloRSSet); // [blue,red,orange]
You can see the output change because there are no orders for the collection The point is that there is no order. In fact, you do see a guarantee that orders do not happen every time - there may be a build that breaks this order in java-8 In fact, Java - 9, for example, is easy to observe - there is a randomization pattern for new collections
If you run multiple times, the results will be different:
Set<String> set = Set.of("red","orange"); System.out.println(set);
Obviously, if you flow from such a set, the order will not be guaranteed, so you will indeed see different running results