Java Arraylist - 将一个复制到另一个而不重复 [英] Java Arraylist - Copy one to another without duplicates

查看:45
本文介绍了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 包含:

I want the resulting ArrayList to contain:

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

我想合并这两个列表并删除值为 0 的列表.如果我这样做了list2.addAll(list1),然后 list2 有两个条目John",值为 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天全站免登陆