My logic is messed up. I am just trying to work out a way to remove duplicates in an ArrayList without using a HashSet.
public static void main(String[] args) {
ArrayList<String> wordDulicate = new ArrayList<String>();
wordDulicate.add("Tom");
wordDulicate.add("Jones");
wordDulicate.add("Sam");
wordDulicate.add("Jamie");
wordDulicate.add("Robie");
wordDulicate.add("Helen");
wordDulicate.add("Tom");
wordDulicate.add("Troy");
wordDulicate.add("Mika");
wordDulicate.add("Tom");
for (String dupWord : wordDulicate) {
if (wordDulicate.equals(dupWord))
System.out.println(wordDulicate.get(dupWord));
}
}
You can create another list, and add items to it, skipping the duplicates: -
ArrayList<String> wordDulicate = new ArrayList<String>();
ArrayList<String> tempList= new ArrayList<String>();
wordDulicate.add("Tom");
wordDulicate.add("Jones");
wordDulicate.add("Sam");
for (String dupWord : wordDulicate) {
if (!tempList.contains(dupWord)) {
tempList.add(dupWord);
}
}
This methodology requires having another list:
ArrayList<String> wordDulicate = new ArrayList<String>();
wordDulicate.add("Tom");
wordDulicate.add("Jones");
wordDulicate.add("Sam");
wordDulicate.add("Jamie");
wordDulicate.add("Robie");
wordDulicate.add("Helen");
wordDulicate.add("Tom");
wordDulicate.add("Troy");
wordDulicate.add("Mika");
wordDulicate.add("Tom");
ArrayList<String> nonDupList = new ArrayList<String>();
Iterator<String> dupIter = wordDulicate.iterator();
while(dupIter.hasNext())
{
String dupWord = dupIter.next();
if(nonDupList.contains(dupWord))
{
dupIter.remove();
}else
{
nonDupList.add(dupWord);
}
}
System.out.println(nonDupList);
Output:
[Tom, Jones, Sam, Jamie, Robie, Helen, Troy, Mika]
You should sort the list and remove the element that is equal to the previous one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With