英文:
How to get unique JSONObject data from list of JSONObject by comparing specific key value?
问题
我需要在Java中按id值比较的方式获得jsonObjectList的唯一值。
我尝试过
List<JSONObject> distinctElements = jsonObjectList.stream()
.filter(distinctByKey(p -> p.getId()))
.collect(Collectors.toList());
我希望上面的示例输出如下:
distinctElements =[
{id: "aaa", key2: "bbb", key3="fff"},
{id: "aab", key2: "ccc", key3="eee"}
]
英文:
I have like,
List<JSONObject> jsonObjectList =[
{id: "aaa",key2: "bbb",key3="eee"},
{id: "aaa",key2: "bbb",key3="fff"},
{id: "aab",key2: "ccc",key3="eee"}
]
I need jsonObjectList unique value comparing by id value in java.
I tried
List<JSONObject> distinctElements = jsonObjectList.stream()
.filter( distinctByKey(p -> p.getId()) )
.collect( Collectors.toList() );
I want the following output for above example:
distinctElements =[
{id: "aaa",key2: "bbb",key3="fff"},
{id: "aab",key2: "ccc",key3="eee"}
]
答案1
得分: 0
你可以尝试使用集合(Set),因为它可以防止重复对象。并且可以使用一些用于 JSON 序列化的库,比如 Gson。
英文:
You can try to use Set as it prevents duplicate objects. And use some libray for JSON serialization, like Gson for example.
答案2
得分: 0
类似的代码:
List<JSONObject> distinctElements = jsonObjectList.stream()
.collect(Collectors.groupingBy(JSONObject::getId, Collectors.toList()))
.values().stream()
.map(list -> list.get(0))
.collect(Collectors.toList());
你还可以实例化一个允许你指定自定义 keyExtractor
的 Set<>
实现。
英文:
Something like:
List<JSONObject> distinctElements = jsonObjectList.stream()
.collect(Collectors.groupingBy(JSONObject::getId, Collectors.toList()))
.values().stream()
.map(list -> list.get(0))
.collect(Collectors.toList());
You can also instantiate a Set<>
implementation that allows you to specify a custom keyExtractor
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论