Skip to content Skip to sidebar Skip to footer

Remove Duplicates Items From Arraylist And Hashmap

I have an arraylist with the name of who pay something, and another arraylist with the cost of each payment. For example: nameArray = Nicola, Raul, Lorenzo, Raul, Raul, Lorenzo, N

Solution 1:

You are adding the entries of the Map to the original Lists. You should clear them first:

nameArray.clear();
priceArray.clear();
for (Map.Entry<String, BigDecimal> entry : totals.entrySet()) {
    nameArray.add(entry.getKey());
    priceArray.add(entry.getValue());
}

Or, if you don't want to overwrite the original Lists, you should create new ArrayLists.

Solution 2:

The easiest way is to implement a Set<String> as a LinkedHashSet<String>() to preserve insert order. This will insure uniqueness in your set.

Sets check hashCode() and the accompanying equals(). Items are considered to be equal if their hashCode() are their same.

If you implement your own class you can override hashCode() and equals() to check for uniqueness as well.

Post a Comment for "Remove Duplicates Items From Arraylist And Hashmap"