您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

java8去掉重复对象的方法有哪些

2024/5/7 5:24:02发布6次查看
一、去除list中重复的stringpublic list<string> removestringlistdupli(list<string> stringlist) { set<string> set = new linkedhashset<>(); set.addall(stringlist); stringlist.clear(); stringlist.addall(set); return stringlist;}
或使用java8的写法:
list<string> unique = list.stream().distinct().collect(collectors.tolist());
二、list中对象去重比如现在有一个 person类:
public class person { private long id; private string name; public person(long id, string name) { this.id = id; this.name = name; } public long getid() { return id; } public void setid(long id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } @override public string tostring() { return "person{" + "id=" + id + ", name='" + name + '\'' + '}'; }}
重写person对象的equals()方法和hashcode()方法:
@override public boolean equals(object o) { if (this == o) return true; if (o == null || getclass() != o.getclass()) return false; person person = (person) o; if (!id.equals(person.id)) return false; return name.equals(person.name); } @override public int hashcode() { int result = id.hashcode(); result = 31 * result + name.hashcode(); return result; }
下面对象去重的代码:
person p1 = new person(1l, "jack"); person p2 = new person(3l, "jack chou"); person p3 = new person(2l, "tom"); person p4 = new person(4l, "hanson"); person p5 = new person(5l, "胶布虫"); list<person> persons = arrays.aslist(p1, p2, p3, p4, p5, p5, p1, p2, p2); list<person> personlist = new arraylist<>(); // 去重 persons.stream().foreach( p -> { if (!personlist.contains(p)) { personlist.add(p); } } ); system.out.println(personlist);
list 的contains()方法底层实现使用对象的equals方法去比较的,其实重写equals()就好,但重写了equals最好将hashcode也重写了。
三、根据对象的属性去重下面要根据person对象的id去重,那该怎么做呢?
写一个方法吧:
public static list<person> removeduplibyid(list<person> persons) { set<person> personset = new treeset<>((o1, o2) -> o1.getid().compareto(o2.getid())); personset.addall(persons); return new arraylist<>(personset); }
通过comparator比较器,比较对象属性,相同就返回0,达到过滤的目的。
再来看比较炫酷的java8写法:
import static java.util.comparator.comparinglong;import static java.util.stream.collectors.collectingandthen;import static java.util.stream.collectors.tocollection;// 根据id去重 list<person> unique = persons.stream().collect( collectingandthen( tocollection(() -> new treeset<>(comparinglong(person::getid))), arraylist::new) );
还有一种写法:
public static <t> predicate<t> distinctbykey(function<? super t, object> keyextractor) { map<object, boolean> map = new concurrenthashmap<>(); return t -> map.putifabsent(keyextractor.apply(t), boolean.true) == null; }// remove duplicate persons.stream().filter(distinctbykey(p -> p.getid())).foreach(p -> system.out.println(p));
以上就是java8去掉重复对象的方法有哪些的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录