Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates from list without reordering in java?

I am trying to remove duplicates from my List object of the type String using Set Interface but the problem i face is that it also reorders my list which is something i don't want. I want to preserver the order of the list and remove duplicates only ?

static List<String>  StopNames = new ArrayList<String>();

StopNames.add(sCurrentLine);

Set<String> set = new HashSet<String>(StopNames);


for (String string : set) {

 System.out.println("Printing Set "+string);

}
like image 764
dev_marshell08 Avatar asked Dec 06 '25 02:12

dev_marshell08


1 Answers

Just switch HashSet for LinkedHashSet, which preserves insertion order while removing duplicates.

like image 77
Louis Wasserman Avatar answered Dec 08 '25 14:12

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!