简体   繁体   中英

How to convert a list of Songs into stream of Strings?

I have a list of songs, which is a class with 3 values: songName , albumName , duration and hash . I have written a function which returns a Stream<String> of all the songs ordered by name. My first idea was this:

public Stream<String> orderedSongNames() {
     return songs.stream().sorted((s1,s2)>s1.getSongName().compareTo(s2.getSongName()));
}

The problem is that in this way, the return value is a Stream<Song> but i want a Stream<String> . does anyone have an idea of how i can solve the problem at hand?

Considering you've overridden the toString method; you can return a stream of each objects String representation like so:

return songs.stream()
            .sorted((s1, s2) -> s1.getSongName().compareTo(s2.getSongName()))
            .map(Object::toString); 

Or if you want to return a Stream<String> where the strings are the song names.

return songs.stream()
            .sorted((s1, s2) -> s1.getSongName().compareTo(s2.getSongName()))
            .map(Song::getSongName); 

If you want to get a Stream<String> of song names sorted by length, then first map the Song instances to String by getting their names.

public Stream<String> orderedSongNames() {
    return songs.stream()
        .map(Song::getSongName)
        .sorted(String::compareTo);
}

You could sort first and map after as some other answers suggest, the result and the process is pretty much the same, but a bit more verbose to write, that's why I reordered these operations:

public Stream<String> orderedSongNames() {
    return songs.stream()
        .sorted(Comparator.comparing(Song::getSongName))
        .map(Song::getSongName);
}

You just need to map it:

public Stream<String> orderedSongNames() {
  return songs.stream()    
    .sorted((s1,s2)>s1.getSongName().compareTo(s2.getSongName()))
    .map((s) -> s.getSongName());
}

You are missing the dash before > :

return songs.stream().sorted((s1,s2)->s1.getSongName().compareTo(s2.getSongName()));
                                    ^--- here

But instead, just do this:

return songs.stream().sorted(Comparator.comparing(Song::getSongName));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM