Big Tree
Big Tree

Reputation: 61

Finding Duplicates in ArrayList

I was wondering how I can do the following: I have 2 arraylists with the values in them associated with each other. i.e. The elements of the arraylists on the same index are related to each other. For example: ArrayList 1 (String arraylist) = [id1, id2, id3, id2, id2, id1]. ArrayList 2 (integer arraylist) = [2, 3, 2, 5, 6, 3].

I want to create 2 new arraylists with the duplicate values not existing anymore. In the above case, the new arraylists should be arraylist1 = [id1, id2, id3]. arraylist2 = [5, 14, 2]. i.e., the values in the second arraylist get added accordingly (since they are associated with the values in the first arraylist on the same index).

I don't understand how to get started with this.

Upvotes: 0

Views: 225

Answers (3)

Sergey Afinogenov
Sergey Afinogenov

Reputation: 2202

Using Stream API:

List<String>  ids    = Arrays.asList("id1", "id2", "id3", "id2", "id2", "id1");
List<Integer> values = Arrays.asList(2, 3, 2, 5, 6, 3);

List<Integer> result = new ArrayList(IntStream.range(0, Math.min(ids.size(), values.size()))
                                              .mapToObj(i -> new Pair<>(ids.get(i), values.get(i)))
                                              .collect(Collectors.groupingBy(Pair::getKey,
                                                                             LinkedHashMap::new,
                                                                             Collectors.summingInt(Pair::getValue)))
                                              .values());

System.out.println(result);

Upvotes: 0

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4329

For example, you can use the following code:

List<String> ids = List.of("id1", "id2", "id3", "id2", "id2", "id1");
List<Integer> values = List.of(2, 3, 2, 5, 6, 3);
Map<String, Integer> result = new LinkedHashMap<>();
for (int i = 0; i < ids.size(); i++) {
    result.merge(ids.get(i), values.get(i), Integer::sum);
}

After that you'll have the following map:

result ==> {id1=5, id2=14, id3=2}

You can extract your lists from this map easily (keySet() and values()).

Upvotes: 1

Osama A.Rehman
Osama A.Rehman

Reputation: 932

Iterate on each index i of the two arrays and accumulate the values based on their ids using a HashMap. Once the accumulation completes, the keys of the hashmap would have the ids without duplicates.

    List<String> ids = Arrays.asList(
            "id1",
            "id2",
            "id3",
            "id2",
            "id2",
            "id1"
    );
    List<Integer> vals = Arrays.asList(2, 3, 2, 5, 6, 3);
    Map<String, Integer> m = new HashMap<>();

    for (int i=0; i<ids.size(); i++) {
        String id=ids.get(i);
        int val = vals.get(i);

        m.put(id, m.getOrDefault(id, 0) + val);
    }

    List<String> newIds = new ArrayList<>(m.keySet());
    List<Integer> newVals = new ArrayList<>(m.values());

Upvotes: 1

Related Questions