Sunday, January 25, 2015

Find duplicate elements in ArrayList

There are four ways is there to find duplicate element in arraylist.
  1. Using ArrayList contains method   
  2. Using HashSet
  3. Using HashMap
  4. Without using above
package com.varasofttech;

import java.util.*;


/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : Displaying the all duplicate elements and how many times it found
*/


class Application {
public static void main(String args[]) {
List<String> names = getNames();
System.out.println("Displaying all names : "+ names);

String duplicateName = "Ranga";
System.out.println("\nFinding the name "+duplicateName +" how many times found");
System.out.println(duplicateName+" found in "+Collections.frequency(names,duplicateName)+" times.");

System.out.println("\nFinding the duplicate elements using ArrayList contains() method ");
List<String> tempNames = new ArrayList<String>();
for(String name : names) {
if(!tempNames.contains(name)) {
tempNames.add(name);
}
}
for(String name : tempNames) {
System.out.println(name+" found in "+ Collections.frequency(names, name) +" times");
}

System.out.println("\nFinding the duplicate elments using HashSet ");
Set<String> filteredSet = new HashSet<String>(names);
printSet(filteredSet,names);

System.out.println("\nFinding the duplicate elments using LinkedHashSet ");
Set<String> listToSet = new LinkedHashSet<String>(names);
printSet(listToSet,names);

System.out.println("\nFinding the duplicate elments using HashMap ");
Map<String,Integer> filteredMap = new HashMap<String,Integer>();
for(String name: names) {
Integer count = filteredMap.get(name);
filteredMap.put(name, (count == null)? 1: count + 1);
}
printMap(filteredMap);

System.out.println("\nFinding the duplicate elments using TreeMap ");
Map<String,Integer> filteredTreeMap = new TreeMap<String,Integer>();
for(String name: names) {
Integer count = filteredTreeMap.get(name);
filteredTreeMap.put(name, (count == null)? 1: count + 1);
}
printMap(filteredTreeMap);
}

private static void printSet(Set<String> filteredSet,List<String> names) {
for(String name : filteredSet) {
System.out.println(name+" found in "+ Collections.frequency(names, name) +" times");
}
}

private static void printMap(Map<String,Integer> filteredMap) {
for(String key: filteredMap.keySet()) {
System.out.println(key+" found in "+ filteredMap.get(key) +" times");
}
}

private static List<String> getNames() {
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Raja");
names.add("Vasu");
names.add("Reddy");
names.add("Manoj");
names.add("Raja");
names.add("Ranga");
names.add("Vasu");
names.add("Yasu");
names.add("Pavi");
names.add("Ranga");
return names;
}
}

0 comments: