Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arraylist - Copy one to another without duplicates

Tags:

java

arraylist

I have an 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));

And another ArrayList:

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

I want the resulting ArrayList to contain:

("John", 2) ("Kane", 4) ("Jen", 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.

like image 890
Harry Avatar asked Dec 03 '22 11:12

Harry


1 Answers

Um it sounds like, in your program logic, creating a

new Person("John", 2)

isn't what you want - is there really a 'new person' called John? or is it the same old John who has a new score? Perhaps you need a function to update the scores in the individual people like

Person.setValue(int)

Sorry if this doesn't actually answer your question, but it's very important to check you have the right kind of data structures.

like image 123
Sanjay Manohar Avatar answered Dec 21 '22 13:12

Sanjay Manohar