Java: Detect Duplicates in Arraylist

Java: Detect duplicates in ArrayList?

Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.

List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);

if(set.size() < list.size()){
/* There are duplicates */
}

Update: If I'm understanding your question correctly, you have a 2d array of Block, as in

Block table[][];

and you want to detect if any row of them has duplicates?

In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:

for (Block[] row : table) {
Set set = new HashSet<Block>();
for (Block cell : row) {
set.add(cell);
}
if (set.size() < 6) { //has duplicate
}
}

I'm not 100% sure of that for syntax, so it might be safer to write it as

for (int i = 0; i < 6; i++) {
Set set = new HashSet<Block>();
for (int j = 0; j < 6; j++)
set.add(table[i][j]);
...

Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.

find duplicate element in array list

You can simply utilize ArrayList#contains to verify if an element already exists within the List.

public boolean addCourse(String course) {
if (courses.contains(course)) {
return false;
}

return courses.add(course);
}

How to detect duplicates in ArrayList Java

Could you please tell me what does this code do for you?

At first glance, I think the problem might be in the line

while (teams.size()>=5)

If I understand it correctly, this loop will continue while the size is at least 5, which it is not at the beginning.

Maybe try to set it to

while (teams.size()<5)

Edit: adding the code from the comment section

  1. add this under the Main class designation

Map<String, List<Team>> countryTeams = new HashMap<String, List<Team>>();

Read about a HashMap here for more info: https://www.w3schools.com/java/java_hashmap.asp


  1. use the HashMap in your code to match teams to countries

    private void createTeam() {
    String country, teamName, coachName, participantName;
    System.out.print("Enter Country Name : ");
    country = sc.nextLine();
    countryTeams.put(country, new ArrayList());
    while (countryTeams.get(country).size()<5) {
    System.out.print("Enter Team Name : ");
    teamName = sc.nextLine();
    participantName = getParticipantName();
    System.out.println("Enter Coach Name : ");
    coachName = sc.nextLine();
    Team team = new Team(country, teamName, coachName, participantName);
    countryTeams.get(country).add(team);

    }
    }

Find duplicate value in array list and print the duplicated value

If you want to reduce some time complexity at the cost of O(n) space, you can use a Set

Set<String> set = new HashSet<>();
for(int i =0; i < list.size(); i++) {
if (set.contains(list.get(i))) {
System.out.println(list.get(i)+" is duplicated");
} else set.add(list.get(i));
}

How to detect duplicates in ArrayList and return new List with duplicated elements

you can use a frequency hashmap to keep track of count, and use that map to filter out the duplicates

      List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("A");
list.add("B");
list.add("C");
list.add("A");
list.add("F");
list.add("Z");
list.add("C");
list.add("H");
Map<String, Integer> freqMap = new HashMap<>();
for (String s: list) {
if(freqMap.containsKey(s)){
freqMap.put(s, freqMap.get(s)+1);
} else {
freqMap.put(s, 1);
}
}

List<String> result = new ArrayList<>();
for(Map.Entry<String, Integer> entry: freqMap.entrySet()){
if(entry.getValue() > 1){
result.add(entry.getKey());
}
}

Identify duplicates in a List

The method add of Set returns a boolean whether a value already exists (true if it does not exist, false if it already exists, see Set documentation).

So just iterate through all the values:

public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates) { 
final Set<Integer> setToReturn = new HashSet<>();
final Set<Integer> set1 = new HashSet<>();

for (Integer yourInt : listContainingDuplicates) {
if (!set1.add(yourInt)) {
setToReturn.add(yourInt);
}
}
return setToReturn;
}

Finding Duplicates in ArrayList

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()).

Find duplicates and remove from ArrayList

I would use Groovy's groupBy/sort combo to achieve what you want:

class Device {

long id
String name
String status

@Override
String toString() { "Device [$id, $status]" }
}

def devices = [
[id : 11, name:'test', status:'pending'],
[id : 13, name : 'abc', status:'new'],
[id : 14, name : 'xyz', status:'pending'],
[id : 11, name : 'test', status:'new'],
[id : 15, name : 'wxy', status:'complete'],
[id : 15, name : 'wxy', status:'pending']
].collect{ it as Device }

def result = devices.groupBy{ it.id }.findResults{ id, devs ->
devs.sort{ [ 'complete', 'pending', 'new' ].indexOf it.status }.first()
}

assert result.toString() == '[Device [11, pending], Device [13, new], Device [14, pending], Device [15, complete]]'


Related Topics



Leave a reply



Submit