0

I have the following list:

ObservableList<String> Books;

I know that if I want to have the sorted list I can write

public ObservableList<String> getBooks() {
    return Books;       
}

Now, my question may be pretty much nonsensical, but... is there a way to achieve the same result as above with streams? Something like

Books
    .stream()
    .sorted();

but then having the stream return me a sorted ObservableList?
I'm just starting to learn about streams and don't know much about it yet, so I was wondering if something like that is possible.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mark
  • 69
  • 1
  • 1
  • 8
  • Your first code isn't even closely related to _sorting_ so you don't need Java streams for that. – Tom Jun 09 '16 at 19:07
  • Your first code block is an accessor/getter that returns an `ObservableList` - it does nothing else. Your second code block seems to sort a stream, but I'm not sure. Your question is confusing/doesn't make sense. – Jonny Henly Jun 09 '16 at 19:07
  • sorry if it wasn't clear, my question was basically how to convert a stream to an observable list – Mark Jun 09 '16 at 19:15

3 Answers3

3

Side note: Books is the wrong naming convention for a variable; use books.


This is indeed possible, using Collectors. Or even Collectors. Assuming ObservableList is a Collection of some sort, you can do the following:

ObservableList<String> hereYouGo = Books.stream()
      .sorted()
      .collect(Collectors.toCollection(ObservableList::new));

Where ObservableList::new is the supplier of an empty ObservableList for the collector. Change this if that's not how your class works.

bcsb1001
  • 2,834
  • 3
  • 24
  • 35
  • This one worked, thanks a lot! I just had to change ObservableList::new to FXCollections::observableArrayList in my class. – Mark Jun 09 '16 at 19:34
1

You need to use a Collector to turn a Stream back into a List. If you don't care what type of List it is, there is a built-in collector:

getBooks().stream().sorted().collect(Collectors.toList())

If it needs to be an ObservableList, you need to invent your own Collector:

getBooks().stream().sorted
    .collect(ObservableList::new, ObservableList::add, ObservableList::addAll);
Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44
  • 3
    [`toCollection()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toCollection-java.util.function.Supplier-) is also a thing. – bcsb1001 Jun 09 '16 at 19:10
1

If you want to sort the list in place, there's no need for streams, you can just call

Collections.sort(books);

If you want to return a new sorted ObservableList<Book> using streams, you can do this:

ObservableList<Book> sortedBooks = books.stream()
        .sorted()
        .collect(Collectors.toList(FXCollections::observableArrayList));
shmosel
  • 49,289
  • 6
  • 73
  • 138