Java的ArrayList的 - 复制一个到另一个没有重复 [英] Java Arraylist - Copy one to another without duplicates

查看:91
本文介绍了Java的ArrayList的 - 复制一个到另一个没有重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的ArrayList

Arraylist<Person> list1 = new ArrayList<Person>();
list1.add(new Person("John", 0));
list1.add(new Person("Kane", 0));
list1.add(new Person("Jen", 0));

和另一个的ArrayList

Arraylist<Person> list2 = new ArrayList<Person>();
list2.add(new Person("John", 2));
list2.add(new Person("Kane", 4));

我要的结果的ArrayList 包含:

("John", 2) ("Kane", 4) ("Jen", 0)

我要合并这两个列表和删除具有值为0。如果我做了那些
list2.addAll(list1的),那么列表2 拥有的2和0值的两个条目约翰。我想删除以0从此列表中值的条目。

I want to merge these two lists and remove the ones that have the value 0. If I did list2.addAll(list1), then list2 has two entries for "John" with the values of 2 and 0. I want to remove the entry with the value of 0 from this list.

推荐答案

好像你要为每个用户的最大值:

Seems like you want the maximum value for each user:

List<Person> all = new ArrayList<Person>();
all.addAll(list1);
all.addAll(list2);

Map<String, Person> map = new HashMap<String, Person>();
for (Person p : all) {
    if (!map.containsKey(p.name) || map.get(p.name).num < p.num) {
        map.put(p.name, p);
    }
}
List<Person> merged = new ArrayList<Person>(map.values());

这篇关于Java的ArrayList的 - 复制一个到另一个没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆