Search code examples
javajava-streamcollectors

How transform a list of objects to a list of strings based on the value of a property in java?


Is there a way how to transform a list of objects to a list of strings based on the value of a property? I have an entity Tag

public class Tag {

    private int tagID;
    private String description;
}

I get a list of tags with their ids and descriptions:

[Tag [tagID=1, description=121], Tag [tagID=1, description=244], Tag [tagID=1, description=331], Tag [tagID=2, description=244], Tag [tagID=2, description=122]]

And what I need is:

List<String> output = ["121,244,331", "244,122"]

So far I put together this:

String description = tags.stream().map(Tag::getDescription).collect(Collectors.joining( ";" ));

outputting a result for one tag

String description = "121,244,331"

Of course, I could run it through a loop and append the result to an array, but I wondered if there is a more ellegant way - even a one-liner?


Solution

  • You can use Collectors.groupingBy to group by tag id and then join description using Collectors.joining

    List<String> res = new ArrayList<>(tagList.stream().collect(
                            Collectors.groupingBy(Tag::getTagID,
                                    Collectors.mapping(Tag::getDescription, Collectors.joining(",")))).values());