【问题标题】:Java JSONObject List comparison using streamJava JSONObject List比较使用流
【发布时间】:2018-05-30 13:12:24
【问题描述】:

我有两个带有 JSONObject 的 ArrayList,我需要比较两者并从中找到不同的项目,到目前为止,这是我的代码,由于某些原因输出我收到的内容不正确。

public static void main(String args[]){

    JSONObject obj1= new JSONObject();
    obj1.put("id", "1DDX");
    obj1.put("crx", "some random string");
    JSONObject obj3= new JSONObject();
    obj3.put("id", "2DDX");
    obj3.put("BMX", "some random data");
    JSONObject obj2= new JSONObject();
    obj2.put("id", "1DDX");
    obj2.put("crx", "some more random string");

    List<JSONObject> list1= new ArrayList<JSONObject>();
    list1.add(obj1);
    list1.add(obj3);
    List<JSONObject> list2= new ArrayList<JSONObject>();
    list2.add(obj2);
    list2.add(obj2);

    List<JSONObject> listcom=list2.stream().filter(json-> list1.contains(json.get("id"))).collect(Collectors.toList());

    System.out.println(listcom);

The output for equal and not equal comparison
[]
The output for 
List<JSONObject> listcom=list2.stream().filter(!json-> list1.contains(json.get("id"))).collect(Collectors.toList());
[{"crx":"some more random string","id":"1DDX"}, {"crx":"some more random string","id":"1DDX"}]

The output what I am looking for is 
{"BMX":"some random data","id":"2DDX"}

【问题讨论】:

  • 那么这里的问题是什么?
  • 我的意思是输出不正确,我在比较两者后从list2中寻找不同的JSONObject

标签: java json arraylist


【解决方案1】:

如果您希望使用 java 流 API 从两个列表中获取不同的 JSONObjects,您可以将两个列表中的流连接成一个流,然后在其上使用 distinct 方法。试试这个:

JSONObject obj1= new JSONObject();
obj1.put("id", "1DDX");
obj1.put("crx", "some random string");
JSONObject obj3= new JSONObject();
obj3.put("id", "2DDX");
obj3.put("BMX", "some random data");
JSONObject obj2= new JSONObject();
obj2.put("id", "1DDX");
obj2.put("crx", "some more random string");

List<JSONObject> list1= new ArrayList<JSONObject>();
list1.add(obj1);
list1.add(obj3);
List<JSONObject> list2= new ArrayList<JSONObject>();
list2.add(obj2);
list2.add(obj2);


Stream<JSONObject> jsonStream = Stream.concat(list1.stream(), list2.stream);

List<JSONObject> listcom= jsonStream.distinct().collect(Collectors.toList());

System.out.println(listcom);

编辑:

如果您尝试从 list1 中检索一个值(如果它对应于 list2 中的值),则您必须映射到该值。试试这个:

List<JSONObject> listcom=list2.stream().filter(json-> list1.contains(json.get("id"))).map(json-> list1.get(json.get("id"))).distinct().collect(Collectors.toList()); 

【讨论】:

  • Dean,对于不同的工作,但是我正在寻找的是,只有一个不在 list2 中的项目,基本上我只需要比较 id 部分而不是 content 部分。 : 这样 {"BMX":"some random data","id":"2DDX"}
  • 在这种情况下,您必须映射到列表一中的结果:
  • 首先,当我使用 list1.contain(json.get("id") 过滤 list2 时,它返回一个空数组 []。此外,map 的第二部分返回编译器错误类型不匹配:无法从 Stream 转换为
猜你喜欢
  • 1970-01-01
  • 2017-09-20
  • 2012-02-06
  • 2011-12-11
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2013-04-18
相关资源
最近更新 更多