java藉助Set集合的去重機制實現物件集合的去重
阿新 • • 發佈:2021-01-22
文章目錄
前言
使用Set集合的去重機制,結合lombok註解實現基本資料型別集合,物件集合的去重
一、引入lombok
在pom.xml檔案中,加入以下依賴:
<!--lombok註解-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</ artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
二、開始執行去重
1.基本資料型別去重
沒有任何要求,直接往HashSet集合裡面塞值即可
package com.lian.entity;
/**
* @author :LSS
* @description: 測試類
* @date :2021/1/21 14:52
*/
public class Test {
public static void main(String[] args) {
//Set基本資料型別測試,無需重寫HashCode和equals,直接套用即可
HashSet<Object> strings = new HashSet<>();
strings.add("張三");
strings.add("lisi");
strings.add("王五");
strings.add("張三");
strings. add(222);
strings.add(213.321);
System.out.println("strings = " + strings);
}
}
測試結果為:
2.物件集合去重的實現
Set物件集合測試,一定要重寫HashCode和equals方法,任何一個不重寫都不會實現去重的效果
建立實體類:此處用到了lombok註解,各註解意思在類中已標明
package com.lian.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //lombok註解,裡面包含HashCode方法,equals方法,toString方法,getter和setter方法
@AllArgsConstructor //有參構造
@NoArgsConstructor //無參構造
public class Student {
private Integer age;
private String name;
}
測試類:
package com.lian.entity;
import java.util.HashSet;
import java.util.Set;
/**
* @author :LSS
* @description: 測試類
* @date :2021/1/21 14:52
*/
public class Test {
public static void main(String[] args) {
//Set物件集合測試,一定要重寫HashCode和equals方法,任何一個重寫都不會實現去重的效果
Student student = new Student(1,"張三");
Student student1 = new Student(1,"張三");
Student student2 = new Student(2,"");
Student student3 = new Student(2,"");
Set<Student> students = new HashSet<>();
students.add(student);
students.add(student1);
students.add(student2);
students.add(student3);
System.out.println("students = "+students);
}
}
測試結果為:
總結
注意:在對物件集合使用Set的特性去重的時候,一定要重寫HashCode方法和equals方法,二者缺一不可!