I have one array list contains object( id,name).need to remove if duplicate names in the list
I need to print only name once if it is repeating
I have one array list contains object( id,name).need to remove if duplicate names in the list
I need to print only name once if it is repeating
Use SET if you want don't want duplicate entries in your list:
Note: You must override equals and hashcode in object(ID,Name) otherwise you will find duplicate object in SET
public static boolean checkDuplicate(ArrayList list) {
HashSet set = new HashSet();
for (int i = 0; i < list.size(); i++) {
boolean val = set.add(list.get(i));
if (val == false) {
return val;
}
}
return true;
}
Use a java.util.Set
instead. It cannot contain duplicates.
Reference: http://docs.oracle.com/javase/6/docs/api/java/util/Set.html
Set<String> myNames = new HashSet<String>();
myNames.add("JAMES");
myNames.add("ELLA");
myNames.add("JAMES");
myNames.size() // will return 2
Use a Set data structure with implementing appropriate Comparator. Run a loop and put your objects in that set. Print this set.
Arraylist provides an iterator that allows to delete the last element returned by the iterator from the list itself. So we just keep track of the names that we've already seen. A Set
implementation is helpful.
Set<String> names = new HashSet<>();
Iterator<MyType> it = getListFromSomewhere().iterator(); // you know how
while(it.hasNext()) {
if (!names.add(it.next().getName()) {
it.remove();
}
}
Hint: adding to a set returns false, if the value is already in the set.
Remarks
Your requirement wasn't that clear: here we keep the first entry with a name and delete all following entries from the list. If the list is not sorted by id, then it is rather random, which entries are kept an which are removed.
You can do it with the help of Set as well as List family
We have seen how to remove duplicates with Set family. We can do it with the help of List family as well. Please refer below code.
package com.rais.util;
import java.util.ArrayList;
import java.util.List;
/**
* @author Rais.Alam
* @project Utils
* @date Dec 18, 2012
*/
public class ConverterUtil
{
/**
* @param args
*/
public static void main(String[] args)
{
List<String> original = new ArrayList<String>();
original.add("Tomcat");
original.add("Jboss");
original.add("GlassFish");
original.add("Weblogic");
original.add("Tomcat");
List<String> newList = removeDuplicates(original);
for (String value : newList)
{
System.out.println(value);
}
}
public static List<String> removeDuplicates(List<String> original)
{
List<String> tempList = new ArrayList<String>();
for (String value : original)
{
if (!tempList.contains(value))
{
tempList.add(value);
}
}
return tempList;
}
}