Page 1 of 1

About Question enthuware.ocpjp.v11.2.1773 :

Posted: Sat Mar 20, 2021 5:03 am
by minajev3
HMMM... played in all that stuff in ide and found strange thing

for example
List<String> l1 = Arrays.asList("a", "b");
List<String> l2 = Arrays.asList("1", "2");
Stream.of(l1).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));
Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));
with lists - if we add more lists in method .of we will get more elements in the stream

int[][] i ={{1,2},{3,4},{5,6}};
Stream.of(i).forEach((y)->System.out.println(Arrays.toString(y)));
Stream.of(i,i).forEach((y)->System.out.println(Arrays.toString(y)));
but with array if we add 2 arrays instead of one we will get 2 elements in stream instead of 3.

Method Stream.of works different when it has one array ?
So it works like more like Arrays.stream.(i) if there is one array element
BUT!!!! If SO, why than .flatMap(x-> Stream.of(x)) and .flatMapToInt(x-> Arrays.stream(x)) inside of the same stream works differently????

Re: About Question enthuware.ocpjp.v11.2.1773 :

Posted: Fri Jun 23, 2023 4:22 pm
by edufin166@yahoo.com
Why
Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x)); - not work...
I have checked in documentation and I found:
static <T> Stream<T> of(T... values) Returns a sequential ordered stream whose elements are the specified values.
If returns a Stream.. Why not works?

I cannot see why. Please, can you help me?

Re: About Question enthuware.ocpjp.v11.2.1773 :

Posted: Fri Jun 23, 2023 9:11 pm
by admin
Please put code within code tags to make it easier to understand for others .

Re: About Question enthuware.ocpjp.v11.2.1773 :

Posted: Thu Aug 22, 2024 5:23 pm
by wojciechblo
The problem is: what is the difference between "x -> Stream.of(x)" and "x.stream()"?
The solution is:
* Stream.of - operates on varing array, so here treats incoming element x as one whole object not as elements of collection. In final result creates stream of lists, with elemets of list type. This lists are different each other so there is no sense to process flatMap on stream with two list objects. So flatMap has nothing to do.
* x.stream() - treats here x as collection and encodes each list into sequence of elements. So flatMap works as is expected.

https://stackoverflow.com/questions/398 ... -stream-of