如何通过比较特定键值从JSONObject列表中获取唯一的JSONObject数据?

huangapple go评论81阅读模式
英文:

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&lt;JSONObject&gt; jsonObjectList =[
      {id: &quot;aaa&quot;,key2: &quot;bbb&quot;,key3=&quot;eee&quot;},
      {id: &quot;aaa&quot;,key2: &quot;bbb&quot;,key3=&quot;fff&quot;},
      {id: &quot;aab&quot;,key2: &quot;ccc&quot;,key3=&quot;eee&quot;}
    ]

I need jsonObjectList unique value comparing by id value in java.

I tried

 List&lt;JSONObject&gt; distinctElements = jsonObjectList.stream()
                                .filter( distinctByKey(p -&gt; p.getId()) )
                                .collect( Collectors.toList() );

I want the following output for above example:

distinctElements =[
  {id: &quot;aaa&quot;,key2: &quot;bbb&quot;,key3=&quot;fff&quot;},
  {id: &quot;aab&quot;,key2: &quot;ccc&quot;,key3=&quot;eee&quot;}
]

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

你还可以实例化一个允许你指定自定义 keyExtractorSet<> 实现。

英文:

Something like:

List&lt;JSONObject&gt; distinctElements = jsonObjectList.stream()
    .collect(Collectors.groupingBy(JSONObject::getId, Collectors.toList()))
    .values().stream()
    .map(list -&gt; list.get(0))
    .collect(Collectors.toList());

You can also instantiate a Set&lt;&gt; implementation that allows you to specify a custom keyExtractor.

huangapple
  • 本文由 发表于 2020年8月6日 22:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63285893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定