Home > Software design >  Best way to convert a List<Object> to List<Object.Property>
Best way to convert a List<Object> to List<Object.Property>

Time:02-24

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

CodePudding user response:

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

And yes, this is contemporary Java. No external libraries used (aside, of course, Album and Song).

CodePudding user response:

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