本文主要是【Java】——java实现list去重(四种方法)的文章,如果有什么需要改进的地方还请大佬指出??
🎬作者简介:大家好,我是听风与他🥇
??博客首页:CSDN主页听风与他
🌄每日一句:狠狠沉淀,顶峰相见
//由于set的无序性,不会保持原来的顺序。
public static List<String> solution1(List<String> list){
Set<String> set = new HashSet<>(list);
List<String> ans = new ArrayList<>(set);
return ans;
}
public static List<String> solution2(List<String> list){
List<String> ans = new ArrayList<>();
for(String i:list) {
if (!ans.contains(i)) {
ans.add(i);
}else {
continue;
}
}
return ans;
}
/**
* java8特性去重
*/
public static List<String> solution3(List<String> list){
List<String> ans = list.stream().distinct().collect(Collectors.toList());
return ans;
}
public static List<String> solution4(List<String> list){
TreeSet<String> t = new TreeSet<>(list);
List<String> ans = new ArrayList<>(t);
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("orange");
list.add("banana");
list.add("grape");
list.add("grape");
System.out.println(solution1(list));
System.out.println(solution2(list));
System.out.println(solution3(list));
System.out.println(solution4(list));
}