In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the methods of List collection to remove weight". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The origin of the problem
In actual development, we often encounter such a difficulty: there are many duplicate objects in a collection container, and the objects in it do not have a primary key, but according to the needs of the business, in fact, we need to filter out objects that are not duplicated according to the conditions.
The more violent method is to judge through a two-tier loop according to business requirements, adding elements without repetition to the new set, and skipping the elements already in the new set.
The operation example is as follows. Create an entity object PenBean with the following code:
/ * * Pen entity * / public class PenBean {/ * * Type * / private String type; / * * Color * / private String color; / /. Omit setter and getter public PenBean (String type, String color) {this.type = type; this.color = color;} @ Override public String toString () {return "PenBean {" + "type='" + type +'\'+ ", color='" + color +'\'+'}';}}
Test the demo as follows:
Public static void main (String [] args) {/ / add information, there is no primary key List penBeanList = new ArrayList () in PenBean; penBeanList.add (new PenBean ("pencil", "black")); penBeanList.add (new PenBean ("pencil", "white"); penBeanList.add (new PenBean ("pencil", "black")); penBeanList.add (new PenBean ("neutral pencil", "white")) PenBeanList.add (newPenBean ("Neutral Pen", "white")); / / New data List newPenBeanList = new ArrayList (); / / traditional repeat judgment for (PenBean penBean: penBeanList) {if (newPenBeanList.isEmpty ()) {newPenBeanList.add (penBean);} else {boolean isSame = false For (PenBean newPenBean: newPenBeanList) {/ / relies on type and color to determine whether there are repeating elements / / if the new collection contains elements, skip if (penBean.getType (). Equals (newPenBean.getType ()) & & penBean.getColor (). Equals (newPenBean.getColor () {isSame = true Break;}} if (! isSame) {newPenBeanList.add (penBean);}
In general, when dealing with objects of array type, you can use this method to deduplicate array elements to filter out arrays that do not contain repeating elements.
Is there a more concise way to write it?
The answer must be yes, and the contains () method in List is!
1. Using contains method in list to remove weight.
Before using contains (), you have to override the equals () method on the PenBean class. Why would you do that? I'll explain it in detail later!
Let's first override the equals () method in the PenBean class, as follows:
@ Overridepublic boolean equals (Object o) {if (this = = o) return true; if (o = = null | | getClass ()! = o.getClass ()) return false; PenBean penBean = (PenBean) o; / / true return Objects.equals (type, penBean.type) & Objects.equals (color, penBean.color) is returned when the contents of type and color are equal.
Modify the test demo as follows:
Public static void main (String [] args) {/ / add information List penBeanList = new ArrayList (); penBeanList.add (new PenBean ("pencil", "black"); penBeanList.add (new PenBean ("pencil", "white"); penBeanList.add (new PenBean ("pencil", "black"); penBeanList.add (new PenBean ("neutral pencil", "white"); penBeanList.add ("neutral pencil", "white")) / / New data List newPenBeanList = new ArrayList (); / / use contain to determine whether there is the same element for (PenBean penBean: penBeanList) {if (! newPenBeanList.contains (penBean)) {newPenBeanList.add (penBean);}} / / output result System.out.println ("= new data =") For (PenBean penBean: newPenBeanList) {System.out.println (penBean.toString ());}}
The output is as follows:
= new data = PenBean {type=' pencil', color='black'} PenBean {type=' pencil', color='white'} PenBean {type=' neutral', color='white'}
If the PenBean object does not override equals (), the contains () method is false! The new data is the same as the source data and does not achieve the goal that we want to remove duplicate elements.
So how does contains () determine that there are the same elements in a collection?
We open the contains () method in ArrayList. The source code is as follows:
Public boolean contains (Object o) {return indexOf (o) > = 0;}
Find the indexOf (o) method and read on. The source code is as follows:
Public int indexOf (Object o) {if (o = = null) {for (int I = 0; I)
< size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) //对象通过 equals 方法,判断是否相同 if (o.equals(elementData[i])) return i; } return -1;} 此时,非常清晰了,如果传入的对象是null,for 循环判断数组中的元素是否有null,如果有就返回下标;如果传入的对象不是null,通过对象的equals()方法,for 循环判断是否有相同的元素,如果有就返回下标! 如果是数组返回的下标,肯定是大于0,否则返回-1! 这就是为什么在List中使用contains()方法,对象需要重写equals()方法的原因! 2、java 8中去重操作 当然,有些朋友可能会想到JDK1.8中的流式写法,例如 jdk1.8 中的集合元素去重写法如下: public static void main(String[] args) { //添加信息 List penBeanList = new ArrayList(); penBeanList.add(new PenBean("铅笔","black")); penBeanList.add(new PenBean("铅笔","white")); penBeanList.add(new PenBean("铅笔","black")); penBeanList.add(new PenBean("中性笔","white")); penBeanList.add(new PenBean("中性笔","white")); //使用java8新特性stream进行List去重 List newPenBeanList = penBeanList.stream().distinct().collect(Collectors.toList()); //输出结果 System.out.println("=========新数据======"); for (PenBean penBean : newPenBeanList) { System.out.println(penBean.toString()); }} 利用 jdk1.8 中提供的Stream.distinct()列表去重,Stream.distinct()使用hashCode()和equals()方法来获取不同的元素,因此使用这种写法,对象需要重写hashCode()和equals()方法! 对PenBean对象重写hashCode()方法,代码如下: @Overridepublic int hashCode() { return Objects.hash(type, color);} 在运行测试demo,结果如下: =========新数据======PenBean{type='铅笔', color='black'}PenBean{type='铅笔', color='white'}PenBean{type='中性笔', color='white'} 即可实现集合元素的去重操作! 那为什么当我们使用String类型的对象作为集合元素时,没有重写呢? 因为 java 中String原生类,已经重写好了,源码如下: public final class Stringimplements java.io.Serializable, Comparable, CharSequence { @Override public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; } @Override public int hashCode() { int h = hash; if (h == 0 && value.length >0) {char val [] = value; for (int I = 0; I < value.length; I +) {h = 31 * h + val [I];} hash = h;} return h;}} 3, HashSet deduplication operation
In the above sharing, we introduced the collection deduplication operation of List! Among them, netizens also mentioned that HashSet can realize the de-duplication of elements!
Indeed, the natural supporting elements of the HashSet collection do not repeat!
The practice code is as follows!
Or first create an object PenBean, and override the equals () and hashCode () methods in Object, as follows:
/ * * Pen entity * / public class PenBean {/ * * Type * / private String type; / * * Color * / private String color; / /. Omit setter and getter public PenBean (String type, String color) {this.type = type; this.color = color;} @ Override public String toString () {return "PenBean {" + "type='" + type +'\'+ ", color='" + color +'\'+'}' } @ Override public boolean equals (Object o) {if (this = = o) return true; if (o = = null | | getClass ()! = o.getClass ()) return false; PenBean penBean = (PenBean) o; / / true return Objects.equals (type, penBean.type) & Objects.equals (color, penBean.color) is returned when the type and color contents are equal. @ Override public int hashCode () {return Objects.hash (type, color);}}
Create a test demo as follows:
Public static void main (String [] args) {/ / add information List penBeanList = new ArrayList (); penBeanList.add (new PenBean ("pencil", "black"); penBeanList.add (new PenBean ("pencil", "white"); penBeanList.add (new PenBean ("pencil", "black"); penBeanList.add (new PenBean ("neutral pencil", "white"); penBeanList.add ("neutral pencil", "white")) / / New data List newPenBeanList = new ArrayList (); / / set deduplication HashSet set = new HashSet (penBeanList); newPenBeanList.addAll (set); / / output result System.out.println ("= new data ="); for (PenBean penBean: newPenBeanList) {System.out.println (penBean.toString ());}}
The output is as follows:
= new data = PenBean {type=' pencil', color='white'} PenBean {type=' pencil', color='black'} PenBean {type=' neutral', color='white'}
Very detailed, the new collection returned has no duplicate elements!
So how does HashSet do it?
Open the source code of HashSet and view the construction method we passed as follows:
Public HashSet (Collection
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.