Skip to content Skip to sidebar Skip to footer

What Is A Efficient Way To Condense A List Of Objects To Based On An Object Value?

I have an ArrayList of Objects. The object has five fields: id, date, name, value, adjusted_value. The list may hold multiple entries with the same name, and I am having trouble de

Solution 1:

You can define a Map where the key is the name and value is the object instance.

Go through the list and for each instance check whether it exists in the map.

If not just add to the map. map.put(instance.name,instance)

If it's already added to the map just

mapInstance=map.get(instance.name);
mapInstance.value+=instance.value;
mapInstance.adjusted_value+=instance.adjusted_value;

After the loop you have the filled map with grouped data

Solution 2:

I would use Guava in two step. Use a NameFunction to convert the list to a Multimap. Use a CondenseFunction to convert the values of the Multimap.

Function<MyClass, String> toName = newFunction(){ 
        publicStringapply(MyClass input){return input.name;}};

  ImmutableListMultimap<String, MyClass> multimap = Multimaps.index(myList, toName);

  Map<String, Collection<MyClass>> map = multimap.asMap();

  Function<Collection<MyClass>, MyClass> condense= newFunction(){ 
        publicMyClassapply(Collection<MyClass>input){
          // create sums here
  }};

   Map<String, MyClass> condensed = Maps.transformValues(map, condense);
   Collection<MyClass> result = condensed.getValues();

Multimaps.index()

Maps.transformValues

Post a Comment for "What Is A Efficient Way To Condense A List Of Objects To Based On An Object Value?"