• 0

[JAVA] Consolidating Duplicates in an Array


Question

I have two sets of arrays:

1. a string array storing the names of objects purchase

2. a double array storing the associated cost of the object

So it should be something like this

cat [ apple, banana, apple ]

amt [ $2, $3, $2 ]

I want to be able to output it so that the duplicates are combined into one entry:

Apple: $4

Banana: $3

Is there an algorithm that can help me combine the duplicates and store it in a new array?

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

You probably want to use a Map here, using the name as the of the object as the key and the price as the value.

On every object, check if the Key already exists, if not, insert it with the corresponding value, it it does, modify the value by adding the prices.

What do you need this for?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.