There are three ways to remove the list and ensure that the order is added:
Mode one, the use of hashset can not add duplicate data characteristics because HashSet can not guarantee the order of addition, so only as a criterion:
Private Static void removeduplicate (list<string> List) { HashSetnew hashset<string> (List.size ()); ListNew arraylist<string>(List.size ()); for (String str:list) { if (Set.add (str)) { result.add (str); } } List.clear (); List.addall (result); }
Mode two, using Linkedhashset cannot add duplicate data and can guarantee the addition order of the characteristics:
Private Static void removeDuplicate2 (list<string> List) { linkedhashsetnew linkedhashset< String>(List.size ()); Set.addall (list); List.clear (); List.addall (set); }
Mode three, using the Contains method of the list to iterate through:
Private Static void removeDuplicate3 (list<string> list) { listnew arraylist<string> (List.size ()); for (String str:list) { if (! Result.contains (str)) { result.add (str); } } List.clear (); List.addall (result); }
Test method:
Public Static voidMain (string[] args) {Finallist<string> list =NewArraylist<string>(); for(inti = 0; i < 1000; i++) {List.add ("Haha-" +i); } LongTime =System.currenttimemillis (); for(inti = 0; I < 10000; i++) {removeduplicate (list); } LongTime1 =System.currenttimemillis (); System.out.println ("Time1:" + (time1-Time )); for(inti = 0; I < 10000; i++) {removeDuplicate2 (list); } LongTime2 =System.currenttimemillis (); System.out.println ("Time2:" + (time2-time1)); for(inti = 0; I < 10000; i++) {removeDuplicate3 (list); } LongTime3 =System.currenttimemillis (); System.out.println ("Time3:" + (time3-time2)); }
Test results:
time1:451
time2:579
time3:62113
Conclusion:
It is recommended to use method one or method two way to carry out the weight
Java list de-weight mode and efficiency comparison