java中List對(duì)象列表實(shí)現(xiàn)去重或取出及排序的方法
前言
因?yàn)樵诿嬖嚨臅r(shí)候碰到幾次list的去重和排序,覺(jué)著有必要給大家總結(jié)一下具體的方法,分享出來(lái)供大家學(xué)習(xí)參考,話(huà)不多說(shuō)了,來(lái)一起看看下面介紹的一種做法:
一、list去重
1.1 實(shí)體類(lèi)Student
List<Student>容量10k以上,要求去重復(fù)。這里Student的重復(fù)標(biāo)準(zhǔn)是屬性相同,因此需要重寫(xiě)equals和hashcode方法,不知道有幾個(gè)可以手寫(xiě)出來(lái)。
student的equals方法:
public void equals(Object o){
if(this == o) retun true;
if(!(o instanceof Student)) return false;
Student stu = (Studend)o;
if(id!=stu.id) return false;
if(age!=stu.age) return false;
return name!=null ? name.equals(stu.name) : stu.name ==null;
}
這里只要記住宗旨是比較Student的屬性即可,如果屬性相同則相等。先考慮地址相等,然后類(lèi)型匹配instanceof。接下來(lái)是各種屬性,int屬性直接雙等號(hào)比較,String類(lèi)型需要判斷是否為null,如果是null則都是null返回true,如果不是null則比較equals。
student的hashcode方法:
public int hashCode(){
int result = id;
reuslt = 31*id +(name!=null?name.hashCode():0);
reuslt = 31*age;
return reuslt;
}
hashCode是為了hash表計(jì)算做輔助,方便快速查找。因此hash算法的結(jié)果要盡量的散列。這里用到31,這個(gè)31在別的博客中看到的原因是這樣的: obj*31==obj<<5-obj.左移5位相當(dāng)乘以2的5次方,就是32.null的hashCode為空。
通過(guò)equals和hashCode的實(shí)現(xiàn)可以發(fā)現(xiàn),如果equals為true,則所有屬性相同,而屬性相同則計(jì)算出的hashCode必然相同。然而hashCode相同,屬性未必一樣,即equals不一定為真。
關(guān)于hashCode的價(jià)值體現(xiàn)并不在這里,而在于HashMap的實(shí)現(xiàn)。HashMap內(nèi)部是通過(guò)鏈表數(shù)組的hash結(jié)構(gòu)來(lái)實(shí)現(xiàn)的,這里就要用到hashcode。
下面是完整的Student代碼:
package com.test.arithmetic.listequals;
/**
* 這里id,name,age相同則Student相同,
* 若有其他相同
* Created by Administrator on 2016/3/29.
*/
public class Student {
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (id != student.id) return false;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
return result;
}
}
1.2通過(guò)HashSet去重
如果你覺(jué)得自己可以hold住一個(gè)完善的hash算法就可以自己去實(shí)現(xiàn)它。這里采用jdk自帶的HashSet來(lái)完成重復(fù)獲取。
先放代碼:
package com.test.arithmetic.listequals;
import org.junit.Assert;
import java.util.*;
/**
* 取出list中重復(fù)的Student對(duì)象
* Created by Administrator on 2016/3/29.
*/
public class ObtainListEquals {
public static void main(String[] args){
//原始數(shù)據(jù)
List<Student> list = new ArrayList<>();
//重復(fù)數(shù)據(jù)
List<Student> list2 = new ArrayList<>();
//填充
for (int i = 0; i < 10 ; i++) {
list.add(new Student(i,"_"+i,18+i));
Random random = new Random();
if (random.nextBoolean()){
list.add(new Student(i,"_"+i,18+i));
}
}
//使用hashset去重復(fù),set為重復(fù)的集合,可以通過(guò)new ArrayList(set)轉(zhuǎn)換成list
HashSet<Student> set = new HashSet<>();
for (Student student : list) {
boolean add = set.add(student);
if (!add){
list2.add(student);
}
}
//比較
Assert.assertEquals(list.size(),list2.size()+set.size());
}
}
去重的原理和簡(jiǎn)單,無(wú)論你僅僅是想把重復(fù)的丟掉,或者將重復(fù)的取出來(lái)。這里去掉的是第二次遇到的對(duì)象,取出的也是第二次遇到的對(duì)象。HashSet中的add方法會(huì)返回一個(gè)Boolean值,如果插入的值已經(jīng)存在,則直接返回false。關(guān)于hashset的源碼放到以后研究。大概的說(shuō),是通過(guò)HashMap的key來(lái)實(shí)現(xiàn)的,而HashMap在1.8中改動(dòng)很大,據(jù)說(shuō)是用紅黑樹(shù)實(shí)現(xiàn)的,提高了get的時(shí)間復(fù)雜度。
二、list對(duì)象排序
同樣list中存放的是Student對(duì)象,我需要一個(gè)規(guī)則來(lái)排序。這個(gè)排序的規(guī)則這里定義為id的比較大小。參考:java中l(wèi)ist排序
2.1 Student對(duì)象實(shí)現(xiàn)Comparable接口
Comparable接口提供一個(gè)比較的compareTo(Object o)方法,通過(guò)返回值>0,=0,<0比較大小。這里由于僅僅把id當(dāng)做比較大小的方法,直接用id做減法,如果是要比較對(duì)象,建議套用this.property.compareTo(o.property) .
package com.test.arithmetic.listequals;
/**
* 這里id,name,age相同則Student相同,
* 若有其他相同
* Created by Administrator on 2016/3/29.
*/
public class Student implements Comparable<Student>{
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (id != student.id) return false;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
return result;
}
@Override
public int compareTo(Student o) {
return this.id-o.id;
}
}
通過(guò)Collections.sort(list)排序:
package com.test.arithmetic.list.sort;
import com.test.arithmetic.list.Student;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 對(duì)list中對(duì)象排序
* Created by Administrator on 2016/3/29.
*/
public class SortList {
List<Student> list;
@Before
public void setUp(){
list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int v = (int)(Math.random() * 100);
list.add(new Student(v,"_"+v,18+v));
}
System.out.println("原list:"+list);
}
//方法一,對(duì)象實(shí)現(xiàn)Comparable接口
@Test
public void byImplements(){
Collections.sort(list);
System.out.println("排序后:"+list);
}
}
2.2 重載sort方法,傳入一個(gè)比較器
Student類(lèi)還是未實(shí)現(xiàn)Comparable接口之前的:
package com.test.arithmetic.list;
/**
* 這里id,name,age相同則Student相同,
* 若有其他相同
* Created by Administrator on 2016/3/29.
*/
public class Student{
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public Student(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (id != student.id) return false;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
在排序的代碼出添加排序規(guī)則:
package com.test.arithmetic.list.sort;
import com.test.arithmetic.list.Student;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 對(duì)list中對(duì)象排序
* Created by Administrator on 2016/3/29.
*/
public class SortList {
List<Student> list;
@Before
public void setUp(){
list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int v = (int)(Math.random() * 100);
list.add(new Student(v,"_"+v,18+v));
}
System.out.println("原list:"+list);
}
//方法一,對(duì)象實(shí)現(xiàn)Comparable接口
@Test
public void byImplements(){
// Collections.sort(list);
System.out.println("排序后:"+list);
}
/*方法二,添加比較器*/
@Test
public void byOverideCompare(){
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getId()-o2.getId();
}
});
System.out.println(list);
}
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
SpringBoot實(shí)現(xiàn)devtools實(shí)現(xiàn)熱部署過(guò)程解析
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)devtools實(shí)現(xiàn)熱部署過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
k8s部署的java服務(wù)添加idea調(diào)試參數(shù)的方法
文章介紹了如何在K8S容器中的Java服務(wù)上進(jìn)行遠(yuǎn)程調(diào)試,包括配置Deployment、Service以及本地IDEA的調(diào)試設(shè)置,感興趣的朋友跟隨小編一起看看吧2025-02-02
mybatis+lombok出現(xiàn)java.lang.IndexOutOfBoundsException錯(cuò)誤及解決
在使用MyBatis和Lombok時(shí),如果遇到j(luò)ava.lang.IndexOutOfBoundsException問(wèn)題,是因?yàn)镸yBatis在嘗試將查詢(xún)結(jié)果封裝成Java對(duì)象時(shí),找不到構(gòu)造函數(shù)中對(duì)應(yīng)的字段,這通常是由于Lombok的@Builder注解生成了全參構(gòu)造函數(shù)2025-02-02
springboot如何實(shí)現(xiàn)導(dǎo)入其他配置類(lèi)
這篇文章主要介紹了springboot如何實(shí)現(xiàn)導(dǎo)入其他配置類(lèi)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
基于Spring Boot使用JpaRepository刪除數(shù)據(jù)時(shí)的注意事項(xiàng)
這篇文章主要介紹了Spring Boot使用JpaRepository刪除數(shù)據(jù)時(shí)的注意事項(xiàng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Spring Boot非Web項(xiàng)目運(yùn)行配置的方法教程
這篇文章主要介紹了Spring Boot非Web項(xiàng)目運(yùn)行配置的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Java中finally和return的關(guān)系實(shí)例解析
這篇文章主要介紹了Java中finally和return的關(guān)系實(shí)例解析,總結(jié)了二者的關(guān)系,然后分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
java中ArrayList和LinkedList的區(qū)別詳解
這篇文章主要介紹了java中ArrayList和LinkedList的區(qū)別詳解,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2021-01-01

