2

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?

2
  • iterate over the list. A dog with this String already exists? add the integer, else, add the dog Commented Apr 8, 2016 at 8:25
  • 6
    I would use a map with Map<String, Dog> where the String is the dogs name. Using a list needs more work to handle the duplicates. Commented Apr 8, 2016 at 8:26

2 Answers 2

4

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.