大家好,又见面了,我是你们的朋友全栈君。
性质
底层采用哈希表算法,无序不可重复
数组去重
public static String[] removeRepeat(String[] array){
Set<String> set = new HashSet<>();
for(int i = 0; i < array.length; i++){
set.add(array[i]);
}
String[] arr = set.toArray(new String[set.size()]);
return arr;
}
public static void main(String[] args) {
String[] arr = {"java","java","C++","python"};
String[] arr2 = removeRepeat(arr);
System.out.println(Arrays.toString(arr2));
}
集合去重
List<String> list = new ArrayList<>();
list.add("aa");
list.add("aa");
list.add("bb");
list.add("cc");
list.add("cc");
System.out.println("去重前list:"+list);
Set<String> set2= new HashSet<>();
set2.addAll(list);
System.out.println("set2:"+set2);
list.clear();
list.addAll(set2);
System.out.println("去重后list:"+list);
TreeSet自动排序
实体类必须实现Comparable接口并重写CompareTo方法,编写排序规则(升序、降序)
public class SetTest {
public static void main(String[] args) {
Set<Person> set3 = new TreeSet<>();
set3.add(new Person("Daniel",22));
set3.add(new Person("Eddie",21));
set3.add(new Person("Jesska",20));
System.out.println(set3);
}
}
class Person implements Comparable<Person>{
String name;
int age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person arg0) {
return this.age - arg0.getAge();
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/133014.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...