简体   繁体   English

如何将歌曲列表转换为字符串流?

[英]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 .我有一个歌曲列表,它是一个具有 3 个值的类: songNamealbumNamedurationhash I have written a function which returns a Stream<String> of all the songs ordered by name.我编写了一个函数,它返回按名称排序的所有歌曲的Stream<String> 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> .问题是,通过这种方式,返回值是一个Stream<Song>但我想要一个Stream<String> does anyone have an idea of how i can solve the problem at hand?有没有人知道我如何解决手头的问题?

Considering you've overridden the toString method;考虑到您已经覆盖了toString方法; 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.或者,如果您想返回一个Stream<String> ,其中字符串是歌曲名称。

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.如果您想获得按长度排序的歌曲名称的Stream<String> ,则首先通过获取它们的名称将Song实例映射String

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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