-2

I'm printing this out functionally.

listaITSAV.stream().sorted().forEach(System.out::println);

But I want to save the sorting of this list in a variable and then print the variable containing the sorting.

note: ListaITSAV is a LinkedList

LinkedList<String> listaITSAV = new LinkedList<String>();
Avalon
  • 34
  • 3

3 Answers3

1

You can use peek() and read this question to know more about it.

listaITSAV.stream().sorted().peek(System.out::println).collect(Collectors.toList());
Bob
  • 157
  • 1
  • 11
1

One way of doing that is storing the stream itself in a variable.

Stream<String> stream = listaITSAV.stream().sorted();

//...some code...

stream.forEach(System.out::println);

NOTE: We cannot perform any further operation on a stream if it has already been operated upon or closed.

For example, attempting to do something like this:

stream.forEach(System.out::println);
stream.forEach(System.out::println);

will result in java.lang.IllegalStateException
with a message, stream has already been operated upon or closed.

Akash Yadav
  • 105
  • 7
0

Assuming listalTSAV is already declared, not null, and is populated with all the values you want sorted, you can simply collect the results and reassign back to the variable if it is not final like so:

LinkedList<String> listaITSAV = new LinkedList<>();
…
listaITSAV = listaITSAV.stream().sorted().collect(Collectors.toCollection(LinkedList::new));

Here is the Oracle documentation for Collectors#toCollection.

Travis Cook
  • 161
  • 9