英文:
How transform a list of objects to a list of strings based on the value of a property in java?
问题
有没有一种方法可以根据属性的值将对象列表转换为字符串列表?我有一个名为Tag的实体类。
public class Tag {
private int tagID;
private String description;
}
我获得了一组带有它们的ID和描述的标签:
[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]]
我需要的是:
List<String> output = ["121,244,331", "244,122"]
到目前为止,我组装了以下代码:
String description = tags.stream().map(Tag::getDescription).collect(Collectors.joining(";"));
这将为一个标签输出结果:
String description = "121,244,331"
当然,我可以通过循环运行它并将结果附加到数组,但我想知道是否有一种更加优雅的方法,甚至是一行代码?
英文:
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?
答案1
得分: 5
你可以使用 Collectors.groupingBy
按标签 ID 进行分组,然后使用 Collectors.joining
连接描述。
List<String> res = new ArrayList<>(tagList.stream().collect(
Collectors.groupingBy(Tag::getTagID,
Collectors.mapping(Tag::getDescription, Collectors.joining(",")))).values());
英文:
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());
答案2
得分: 2
我认为你正在寻找以下内容:
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());
输出
[121;244;331, 244;122]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论