How to Remove Duplicates from ArrayList in Java

There are multiple way to Remove Duplicates from ArrayList in Java.

Use for loop :-

  • Here we use one for loop to inside antoher for loop. from first for loop we iterate list data which index start from 0.inside second for loop we iterate list elements which index start from i+1.
  • Now inside if condition we compare both for loop elements from list.get() method.
  • If list of elements same then use remove method for removing data.

IndexOf() method:-

  • First we convert list of data to object array from toArray() method.
  • Now for each loop convert object array to object data.
  • Inside if condition check first object value not equal to last object value.
  • From remove method we are removing last object value which is duplicate elements.

Use HashSet method :-

  • HashSet in Java is a class from the Collections Framework.
  • Here first we create HashSet object.
  • Now pass list data to HashSet.it is not allow duplicate elements.

Use distinct() method:-

  • Here first we stream the list of data.streams are the sequence of elements that are read from the source and written to the destination.
  • distinct() method returns a stream consisting of removing duplicate elements from the collection.distinct() is the method of Stream interface.
  • From Collectors.toList() method return element in list format.
				
					import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class RemoveDuplicateData {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(3);
		list.add(4);
		list.add(2);
		list.add(5);

		// for loop method
		for (int i = 0; i < list.size(); i++) {
			for (int j = i + 1; j < list.size(); j++) {
				if (list.get(i) == list.get(j)) {
					list.remove(j);
				}
			}

		}
		System.out.println("using for loop:- " + list);

		// indexOf method
		Object o[] = list.toArray();
		for (Object s : o) {
			if (list.indexOf(s) != list.lastIndexOf(s)) {
				list.remove(list.lastIndexOf(s));
			}
		}
		System.out.println("using indexOf method:- " + list);

		// hashset method
		Set st = new HashSet();
		st.add(list);
		System.out.println("using hashset method :- " + st);

		// distinct method
		List<Integer> pd = list.stream().distinct().collect(Collectors.toList());
		System.out.println("using distict method:- " + pd);
	}

}
				
			

output :-

using for loop:- [1, 2, 3, 4, 5]
using indexOf method:- [1, 2, 3, 4, 5]
using hashset method :- [[1, 2, 3, 4, 5]]
using distict method:- [1, 2, 3, 4, 5]