'Best way to convert a List<Object> to List<Object.Property>
Consider the following use case:
I have List<Song> which holds an ArrayList.
I want to translate the above on-the-fly to List<String> which may be an ArrayList where String is used to store the name of the song (Property: string songName).
I am currently using the following method:
List<String> songNames = new ArrayList<>();
album.getSongs().forEach(song -> songNames.add(song.getSongName()));
model.setSongs(songNames);
Is there any better (preferrably in-place) way to populate model.setSongs()?
PS: I think overloading toString to return the name might be useful, but I can't figure out how.
Oh yes, and I am also a beginner in Java
Solution 1:[1]
Try this:
final var songNames = album.getSongs()
.stream()
.map( Song::getSongName )
.toList();
songNames is immutable in this case; if you insist in having an ArrayList, it looks like this:
final var songNames = new ArrayList<>( album.getSongs()
.stream()
.map( Song::getSongName )
.toList() );
'In-place' would be this:
model.setSongs( album.getSongs()
.stream()
.map( Song::getSongName )
.toList() );
And yes, this is contemporary Java. No external libraries used (aside, of course, Album and Song).
By the way, overwriting toString() to get the name of a song is not really a good idea (at least not in most cases). toString() provides the "string representation" of an instance – if its name alone really represents the song in your context, then you could overwrite toString(). But usually you expect something like "Song [Name: name, Duration: 4:33, Interpret: someone, …]" as the output of toString().
Solution 2:[2]
You can use a stream in which you map each song to it's name:
final var songNames = album.getSongs.stream().map(Song::getName).collect(Collectors.toList());
model.setSongs(songNames);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kristian Ferki? |
