简体   繁体   中英

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?

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

I think you are looking to:

List<String> result = tags.stream()
        .collect(Collectors.groupingBy(Tag::getTagID))
        .values()
        .stream()
        .map(t -> t.stream().map(Tag::getDescription).collect(Collectors.joining( ";" )))
        .collect(Collectors.toList());

Output

[121;244;331, 244;122]

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