tasgr86
tasgr86

Reputation: 309

Arraylist of objects - how to add objects with duplicate values

I have an ArrayList of Dog that looks like this,

ArrayList<Dog> array=new ArrayList<>();

   array.add(new Dog("one", 10));
   array.add(new Dog("two", 20));
   array.add(new Dog("one", 40));

Class Dog takes a String and a Double as parameters.I'm trying to merge those ArrayList objects that have duplicate String values.At the same time i need to add their Double values. So in this example i want to get a new ArrayList that will have two Dog objects like this,

Dog ("one", 50)
Dog ("two", 20)

I've already managed to add objects with duplicate values but i'm having trouble in adding their double values.Any suggestions?

Upvotes: 2

Views: 480

Answers (2)

Siddharth
Siddharth

Reputation: 396

You can use a Map to track Dog objects as you encounter them while you go through the List one by one in a for loop.

List<Dog> array=new ArrayList<>();

array.add(new Dog("one", 10));
array.add(new Dog("two", 20));
array.add(new Dog("two", 120));
array.add(new Dog("one", 40));

Map<String, Dog> map = new HashMap<>(); //Map with key=StringField and value=Dog object

for(Dog d : array){

    Dog dog = map.get(d.getStringField()); 
    if(dog != null){ //If dog object is already in map
        dog.setDoubleField(dog.getDoubleField()+d.getDoubleField()); //add the double value of d to it.
    }else{
        map.put(d.getStringField(), d); //add the dog object with key as stringField
    }
}

System.out.println(Arrays.asList(map.values().toArray()));

Upvotes: 1

wero
wero

Reputation: 32980

You can combine the dogs using Map.merge and a remapping function:

Map<String,Dog> map = new HashMap<>();
array.stream().forEach(dog -> map.merge(dog.name, dog, (d1, d2) -> {
    return new Dog(d1.name, d1.count + d2.count);
}));

ArrayList<Dog> mergedDogs = new ArrayList<>(map.values());

Upvotes: 4

Related Questions