Pages

How to get distinct values from a List ?

 How to get distinct values from a List ?

In Java , we can get distinct values from a list using below few different methods:

1) Using for loop

2) Using HashSet

3) Using Java Streams

import java.util.ArrayList;

import java.util.HashSet;

import java.util.List;

import java.util.stream.Collectors;

public class removeListDuplicates {

public static void main(String[] args) {

//create a list

List<String> l=new ArrayList<String>();

//add values to list

l.add("First");;

l.add("Second");

l.add("Third");

l.add("Fourth");

l.add("Fifth");

l.add("Second");

l.add("Fourth");

//Final list of values

System.out.println("List="+l);

//get distinct values from list using for loop

List<String> distinct=new ArrayList<String>();

List<String> duplicate=new ArrayList<String>();

for(int i=0;i<l.size();i++) {

if(!distinct.contains(l.get(i))) {

distinct.add(l.get(i));

}else {

duplicate.add(l.get(i));

}

}

System.out.println("distinct="+distinct);

System.out.println("duplicate="+duplicate);

//get distinct values from list using HashSet

System.out.println("<-----get distinct values from list using HashSet----->");

HashSet<String>  uniqueValues=new HashSet<String>(l);

for(String uniqueValue : uniqueValues) {

System.out.println("List values="+uniqueValue);

}

//get distinct values from list using Java Streams

System.out.println("<-----get distinct values from list using Java Streams----->");

List<String> listDistinct =l.stream().distinct().collect(Collectors.toList());

System.out.println("List values using stream="+listDistinct);

}

}

Output:

Get distinct values from list
remove duplicates in list
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.