我有两个带有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"}
答案 0 :(得分:0)
如果您希望使用java streaming 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());