-1

I wonder stream().toArray function always guarantee order or not.

List<String> list = new ArrayList<String>();
list.add("brace open");
list.add("I am a boy");
list.add("or");
list.add("she is a teacher");
list.add("brace close");
list.add("and");
list.add("human is type");
String[] array = list.stream().toArray(String[]::new);

array = ["brace open", "I am a boy", "or", "she is a teacher", "brace close", "and", "human is type"];

Can I expect ordered result always?

  • 1
    yes because it's a stream from a list...streams maintain their order if the collection that is being streamed maintains order – RobOhRob Dec 14 '20 at 04:12
  • 3
    Does this answer your question? [Java stream order of processing](https://stackoverflow.com/questions/38262303/java-stream-order-of-processing) – samabcde Dec 14 '20 at 04:18

2 Answers2

0

Guess the javadocs clearly explains it,

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not.

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35
0

If you call stream() on a HashSet the stream will be unordered while calling stream() on a List returns an ordered stream.

Note that you can call unordered() to release the ordering contract and potentially increase performance. Once the stream has no ordering there is no way to reestablish the ordering. (The only way to turn an unordered stream into an ordered is to call sorted, however, the resulting order is not necessarily the original order).

See also the “Ordering” section of the java.util.stream package documentation https://docs.oracle.com/javase/8/docs/api/?java/util/stream/package-summary.html It says: "Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not."

  • So Dont stream() function guarantee order completely? It just changes from list added in order to array by using stream, then what difference list.toArray(new String[list.size()]); and list.stream().toArray(String[]::new ) ? Is it difference two result by order always? – art.dev.yoo Dec 14 '20 at 04:42