Home > Back-end >  One liner for comparing by property and returning a stream?
One liner for comparing by property and returning a stream?

Time:01-09

Is it possible to sort and return a stream in one line as in the following?

//@Getter..
public List<Actor> actors;

public Stream<Actor> actors() {
    //can these two lines be combined somehow?
    actors.sort(Comparator.comparing(Actor::getName));
    return actors.stream();
}

CodePudding user response:

you can do it like this:

return actors.stream().sorted(Comparator.comparing(Actor::getName));

The sort Method of a List will return void, so there is no chance to concat.

Greetings

CodePudding user response:

Streams has a sorted method

actors.stream().sorted(Comparator.comparing(Actor::getName))

Note: This will not sort the List. And will only sort the returned stream.

  •  Tags:  
  • java
  • Related