Pages

How to Remove duplicates from String Array in Java?

 How to Remove duplicates from String Array ?

>>There are different ways we can remove duplicates in string array. By using Set, LinkedHashset, Streams,HashMap etc.,. we can remove duplicates in string array.

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class removeStringArrayDuplicates {
public static void main(String[] args) {
String data= "Java DOTNET SQL Angular Java SQL";
String words[]=data.split(" ");
Map<String,Integer> hm=new HashMap<String,Integer>();
for(String word : words) {
if(hm.containsKey(word)) {
hm.put(word, hm.get(word)+1);
}
else {
hm.
put(word, 1);
}
}
System.out.println(
"Final Hashmap="+hm);
System.out.println(
"<<--------------------------------------------->>");
System.out.print("Final duplicate values using Hash Map=");
Set<String> keys=hm.keySet();
for(String key : keys) {
if(hm.get(key)>1) {
System.out.print(key+" ");
}
}
System.out.println();
System.out.print("Final unique values using Hash Map=");
for(String key : keys) {
if(hm.get(key)<=1) {
System.out.print(key+" ");
}
}

System.out.println();
System.out.println(
"<<--------------------------------------------->>");
Set<String> s=new HashSet<>();
for(String w :words) {
s.add(w);
}
System.out.println("Final unique values using hash set="+s);

System.out.println(
"<<--------------------------------------------->>");
Set<String> lhs=new LinkedHashSet<>();
for(String w :words) {
lhs.add(w);
}
System.out.println("Final unique values using Linked hash set="+lhs);

System.out.println(
"<<---------------------------------------------------->>");
List<String> list = Arrays.stream(words).distinct().collect(Collectors.toList());
System.out.println("Final array with unique values using streams=" + list);

}
}
Output:

java remove duplicates in string array

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.