java
/**
* 数组去重
*/
public class ArrayDistinct {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","张三");
jsonObject1.put("age",20);
jsonObject1.put("gender","男");
jsonObject1.put("money",200);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","李四");
jsonObject2.put("age",20);
jsonObject2.put("gender","女");
jsonObject2.put("money",100);
list.add(jsonObject1);
list.add(jsonObject1);
list.add(jsonObject2);
System.out.println(list);
}
}
输出数组结果:
javascript
[
{
"gender": "男",
"money": 200,
"name": "张三",
"age": 20
},
{
"gender": "男",
"money": 200,
"name": "张三",
"age": 20
},
{
"gender": "女",
"money": 100,
"name": "李四",
"age": 20
}
]
预期结果:
javascript
[{"gender":"男","money":200,"name":"张三","age":20}, {"gender":"女","money":100,"name":"李四","age":20}]
实现方法:在输出前加上以下代码即可实现:
java
// 转为stream,利用distinct方法去重
list = list.stream().distinct().collect(Collectors.toList());
完整代码:
java
public class ArrayDistinct {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name","张三");
jsonObject1.put("age",20);
jsonObject1.put("gender","男");
jsonObject1.put("money",200);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name","李四");
jsonObject2.put("age",20);
jsonObject2.put("gender","女");
jsonObject2.put("money",100);
list.add(jsonObject1);
list.add(jsonObject1);
list.add(jsonObject2);
System.out.println("去重前:"+list);
// 转为stream,利用distinct方法去重
list = list.stream().distinct().collect(Collectors.toList());
System.out.println("去重后:"+list);
}
}
输出: