set列表对象去重_java中List对象列表实现去重或取出及排序的方法

前言

因为在面试的时候碰到几次list的去重和排序,觉着有必要给大家总结一下具体的方法,分享出来供大家学习参考,话不多说了,来一起看看下面介绍的一种做法:

一、list去重

1.1 实体类Student

List容量10k以上,要求去重复。这里Student的重复标准是属性相同,因此需要重写equals和hashcode方法,不知道有几个可以手写出来。

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的属性即可,如果属性相同则相等。先考虑地址相等,然后类型匹配instanceof。接下来是各种属性,int属性直接双等号比较,String类型需要判断是否为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表计算做辅助,方便快速查找。因此hash算法的结果要尽量的散列。这里用到31,这个31在别的博客中看到的原因是这样的:obj*31==obj<<5-obj.左移5位相当乘以2的5次方,就是32.null的hashCode为空。

通过equals和hashCode的实现可以发现,如果equals为true,则所有属性相同,而属性相同则计算出的hashCode必然相同。然而hashCode相同,属性未必一样,即equals不一定为真。

关于hashCode的价值体现并不在这里,而在于HashMap的实现。HashMap内部是通过链表数组的hash结构来实现的,这里就要用到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通过HashSet去重

如果你觉得自己可以hold住一个完善的hash算法就可以自己去实现它。这里采用jdk自带的HashSet来完成重复获取。

先放代码:

package com.test.arithmetic.listequals;

import org.junit.Assert;

import java.util.*;

/**

* 取出list中重复的Student对象

* Created by Administrator on 2016/3/29.

*/

public class ObtainListEquals {

public static void main(String[] args){

//原始数据

List list = new ArrayList<>();

//重复数据

List 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,18+i));

}

}

//使用hashset去重复,set为重复的集合,可以通过new ArrayList(set)转换成list

HashSet 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());

}

}

去重的原理和简单,无论你仅仅是想把重复的丢掉,或者将重复的取出来。这里去掉的是第二次遇到的对象,取出的也是第二次遇到的对象。HashSet中的add方法会返回一个Boolean值,如果插入的值已经存在,则直接返回false。关于hashset的源码放到以后研究。大概的说,是通过HashMap的key来实现的,而HashMap在1.8中改动很大,据说是用红黑树实现的,提高了get的时间复杂度。

二、list对象排序

同样list中存放的是Student对象,我需要一个规则来排序。这个排序的规则这里定义为id的比较大小。参考:java中list排序

2.1 Student对象实现Comparable接口

Comparable接口提供一个比较的compareTo(Object o)方法,通过返回值>0,=0,<0比较大小。这里由于仅仅把id当做比较大小的方法,直接用id做减法,如果是要比较对象,建议套用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{

int id;

String name;

int age;

public Student(int id,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;

}

}

通过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;

/**

* 对list中对象排序

* Created by Administrator on 2016/3/29.

*/

public class SortList {

List 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);

}

//方法一,对象实现Comparable接口

@Test

public void byImplements(){

Collections.sort(list);

System.out.println("排序后:"+list);

}

}

2.2 重载sort方法,传入一个比较器

Student类还是未实现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,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 +

'}';

}

}

在排序的代码出添加排序规则:

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;

/**

* 对list中对象排序

* Created by Administrator on 2016/3/29.

*/

public class SortList {

List 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,18+v));

}

System.out.println("原list:"+list);

}

//方法一,对象实现Comparable接口

@Test

public void byImplements(){

// Collections.sort(list);

System.out.println("排序后:"+list);

}

/*方法二,添加比较器*/

@Test

public void byOverideCompare(){

Collections.sort(list,new Comparator() {

@Override

public int compare(Student o1,Student o2) {

return o1.getId()-o2.getId();

}

});

System.out.println(list);

}

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当需要对List进行去重操作时,Java有多种方法可以实现,下面介绍5种常用的去重方法及它们的效率对比: 1.使用Set去重:将List转化为Set,再将Set转化回List实现去重。这种方法简单易行,但是会改变元素原本的顺序。同时,如果要保留原来的顺序,可以使用LinkedHashSet。 2.使用contains方法去重使用一个新的List,遍历原List元素,判断新List是否已经存在该元素,如果不存在则添加到新List。这种方法简单,但是效率不高,因为每次contains方法都需要遍历新List。 3.使用TreeSet去重:将List转化为TreeSet,再将TreeSet转化回List实现去重。这种方法可以保留原来的顺序,但是效率不高,因为每次添加元素都需要进行排序。 4.使用Stream去重使用Java 8的Stream API,将List转化为Stream,使用distinct方法实现去重,再将Stream转化回List。这种方法简单易行,但是效率不高,因为需要进行Stream的转化和排序操作。 5.使用HashMap去重使用一个新的List一个HashMap,遍历原List元素,将元素作为Key添加到HashMap,如果返回值为null则说明该元素不存在,将该元素添加到新List。这种方法效率较高,但是需要额外的空间存储HashMap。 综上所述,如果不考虑空间复杂度,使用HashMap去重是最优的选择。如果需要保留原有的顺序,可以使用LinkedHashSet。如果需要简单易行的方法,可以使用Set或Stream。而使用contains方法和TreeSet的效率较低,不建议使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值