對List去重並保證新增順序主要有三種方式
阿新 • • 發佈:2018-11-16
方式一,利用HashSet不能新增重複資料的特性 由於HashSet不能保證新增順序,所以只能作為判斷條件:
private static void removeDuplicate(List<String> list) {
HashSet<String> set = new HashSet<String>(list.size());
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (set.add(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
方式二,利用LinkedHashSet不能新增重複資料並能保證新增順序的特性 :
private static void removeDuplicate(List<String> list) {
LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
set.addAll(list);
list.clear();
list.addAll(set);
}
方式三,利用List的contains方法迴圈遍歷:
private static void removeDuplicate(List<String> list) {
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (!result.contains(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
準備測試程式:
private static void main(String[] args) {
final List<String> list = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
list.add("haha-" + i);
}
<span class="hljs-keyword">long</span> time = System.currentTimeMillis();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10000</span>; i++) {
removeDuplicate(list);
}
<span class="hljs-keyword">long</span> time1 = System.currentTimeMillis();
System.out.println(<span class="hljs-string">"time1:"</span>+(time1-time));
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10000</span>; i++) {
removeDuplicate2(list);
}
<span class="hljs-keyword">long</span> time2 = System.currentTimeMillis();
System.out.println(<span class="hljs-string">"time2:"</span>+(time2-time1));
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10000</span>; i++) {
removeDuplicate3(list);
}
<span class="hljs-keyword">long</span> time3 = System.currentTimeMillis();
System.out.println(<span class="hljs-string">"time3:"</span>+(time3-time2));
}
結果為:
time1:329
time2:292
time3:17315
總結:從便捷以及效率上,方式二是最佳選擇,具體原因可以參考HashMap的儲存方式
http://www.cnblogs.com/chenssy/p/3521565.html