对List数据的去冗,分两种情况,话不多说,直接上代码:
第一种:
package com.example.mylist; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<TestBean> testBeanList=new ArrayList<>(); testBeanList.add(new TestBean("111","222")); testBeanList.add(new TestBean("111","222")); testBeanList.add(new TestBean("111","222")); testBeanList.add(new TestBean("111","222")); testBeanList.add(new TestBean("111","222")); testBeanList.add(new TestBean("111","222")); LinkedHashSet<TestBean> hashSet = new LinkedHashSet<>(testBeanList); List<TestBean> beanList = new ArrayList<>(hashSet); Log.e("======",beanList.toString()); } }
package com.example.mylist; import androidx.annotation.Nullable; public class TestBean { private String name; private String age; public TestBean(String name, String age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "TestBean{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } @Override public boolean equals(@Nullable Object obj) { TestBean testBean = (TestBean) obj; return name.equals(testBean.getName()) && age.equals(testBean.getAge()); } @Override public int hashCode() { String str = name + age; return str.hashCode(); } }
输出结果如下:
第二种情况:
输出结果:
总结: