如何在Java中将集合列表转换为唯一的数组或列表?

如何在Java中将集合列表转换为唯一的数组或列表?,java,arrays,list,multidimensional-array,set,Java,Arrays,List,Multidimensional Array,Set,我只是在这个方法中,我寻找每个产品带来的所有评论,但结果将是一个数组,因此我只是想知道如何以一种简单的方式将其转化为一个独特的数组 以下是我大摇大摆的结果: "all_comments": [ [ "comment 1 test a ver si sirve", "comment 34 test a ver si sirve test 34" ], ["comment 2xxxxxxxxx"

我只是在这个方法中,我寻找每个产品带来的所有评论,但结果将是一个数组,因此我只是想知道如何以一种简单的方式将其转化为一个独特的数组

以下是我大摇大摆的结果:

"all_comments": [
  [
    "comment 1 test a ver si sirve",
    "comment 34 test a ver si sirve test 34"
  ],
  ["comment 2xxxxxxxxx",
    "comment yyyyyyyy"
  ]
]
这个想法是要有一种:

"all_comments": [
  "comment 1 test a ver si sirve",
  "comment 34 test a ver si sirve test 34",
  "comment 2xxxxxxxxx",
  "comment yyyyyyyy"
]
在我的一个服务实现上,我设置的方法具有以下逻辑:

服务:

Map getAllComments()引发GeneralException
服务实施:

@覆盖
公共映射getAllComments()引发GeneralException{
Map comments=newhashmap();
List commentsSet=productRepository.findAll().stream()
.map(product->product.getCommentsSet())
.collect(Collectors.toList());
comments.put(“所有注释”,commentsSet.stream()
.map(passList->passList.stream()
.map(passSet->passSet.getCommentBody())
.collect(Collectors.toList());
返回评论;
}
您可以使用以下方法:

publicstaticvoidmain(字符串[]args){
最终列表注释=List.of(
“马修斯”、“兰博”名单,
列表(“堆栈溢出”、“Github”),
列表(“我在做什么?”,“这是一条评论!”),
名单(“吉特胡布”、“兰博”);
最终设置allComments=comments.stream()
.flatMap(列表::流)
.collect(收集器.toSet());
System.out.println(所有注释);
}
注:

这不是有效的JSON{}表示对象

您需要的是:

"all_comments": [
    "comment 1 test a ver si sirve",
    "comment 34 test a ver si sirve test 34",
    "comment 2xxxxxxxxx",
    "comment yyyyyyyy"
]

这是一个有效的字符串数组。

我刚刚修改了一些想法,比如将变量commentset of List of class type Comments更改为type class Comments的列表。 然后修改从存储库中带来的每个产品的逻辑,使用flatMap将获得的集合列表展平为一个数组,然后将其收集到一个列表中。 种类:

@覆盖
公共映射getAllComments()引发GeneralException{
Map comments=newhashmap();
List commentsSet=productRepository.findAll().stream()
.map(product->product.getCommentsSet())
.flatMap(x->x.stream())
.collect(Collectors.toList());
comments.put(“所有注释”,commentsSet.stream()
.map(passList->passList.getCommentBody())
.collect(Collectors.toList());
返回评论;
}
其结果是:

"all_comments": [
  "comment 1 test a ver si sirve",
  "per fecto prueba 3",
  "comment 34 test a ver si sirve test 34"
]
可以使用方法将集合列表展平为单个数组,如下所示:

List commentsSet=List.of(
新建LinkedHashSet(列表中的(
“评论1测试一个版本”,
“意见34测试a版本(测试34”),
新建LinkedHashSet(列表中的(
“评论2xxxxxxxxx”,
“注释YYYYYY”);
字符串[]commentsArr=commentsSet.stream()
.flatMap(集合::流)
.toArray(字符串[]::新建);
Arrays.stream(commentsArr.forEach(System.out::println);
//评论1测试一个版本
//意见34测试a版本sirve测试34
//评论2xxxxxxxxx
//注释yyyyyyy


另请参见:

非常感谢Matheus rambo,根据您的回答,我确实得到了自己的解决方案。请检查它。这是否回答了您的问题?
"all_comments": [
  "comment 1 test a ver si sirve",
  "per fecto prueba 3",
  "comment 34 test a ver si sirve test 34"
]