Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find multiples of the same integer in an arraylist?

My problem is as follows. I have an arraylist of integers. The arraylist contains 5 ints e.g[5,5,3,3,9] or perhaps [2,2,2,2,7]. Many of the arraylists have duplicate values and i'm unsure how to count how many of each of the values exist.

The problem is how to find the duplicate values in the arraylist and count how many of that particular duplicate there are. In the first example [5,5,3,3,9] there are 2 5's and 2 3's. The second example of [2,2,2,2,7] would be only 4 2's. The resulting information i wish to find is if there are any duplicates how many of them there are and what specific integer has been duplicated.

I'm not too sure how to do this in java.

Any help would be much appreciated. Thanks.

like image 975
Julio Avatar asked Apr 29 '10 22:04

Julio


People also ask

How do you find duplicates in ArrayList?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

Can ArrayList contain duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Can ArrayList have multiple values?

ArrayList<Object> list = new ArrayList<Object>(); The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.

Can we get index from value in ArrayList in Java?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.


1 Answers

To me, the most straightforward answer, would be using the Collections.frequency method. Something along the lines of this:

// Example ArrayList with Integer values
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(7);

Set<Integer> noDupes = new HashSet<Integer>();
noDupes.addAll(intList); // Remove duplicates

for (Integer i : noDupes) {
    int occurrences = Collections.frequency(intList, i);
    System.out.println(i + " occurs " + occurrences + " times.");
}

If you want to, you could map each Integer with its number of occurrences:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : noDupes) {
    map.put(i, Collections.frequency(intList, i));
}
like image 52
Lars Andren Avatar answered Oct 23 '22 15:10

Lars Andren