List集合去重、集合中根据对象的某个属性去重的方法
根据集合中的指定节点去重的方法:
C#示例:
定义一个User对象:
class User { public string name { get; set; } public int Age { get; set; } }
继承:IEqualityComparer接口
public class Dis : IEqualityComparer<User> { public bool Equals(User x, User y) { return x.name == y.name; } public int GetHashCode(User obj) { return obj.name.GetHashCode(); } }
获取根据name去重的数据:
class Program { static void Main(string[] args) { var ls = new List<User>(); ls.Add(new User { name = "aa", Age = 10 }); ls.Add(new User { name = "aa", Age = 3 }); ls.Add(new User { name = "bb", Age = 5 }); ls.Add(new User { name = "cc", Age = 20 }); var disLs = ls.Distinct(new Dis()).ToList(); foreach (var item in disLs) { Console.WriteLine($"name:{item.name} age:{item.Age}"); } Console.ReadLine(); } }
结果显示:
也可以验证类自己继承接口:IEqualityComparer<User>
public class User : IEqualityComparer<User> { public string name { get; set; } public int Age { get; set; } public bool Equals(User x, User y) { return x.name == y.name; } public int GetHashCode(User obj) { return obj.name.GetHashCode(); } }
调用方法传入一个User对象:
class Program { static void Main(string[] args) { var ls = new List<User>(); ls.Add(new User { name = "aa", Age = 10 }); ls.Add(new User { name = "aa", Age = 3 }); ls.Add(new User { name = "bb", Age = 5 }); ls.Add(new User { name = "cc", Age = 20 }); var disLs = ls.Distinct(new User()).ToList(); foreach (var item in disLs) { Console.WriteLine($"name:{item.name} age:{item.Age}"); } Console.ReadLine(); } }
JAVA示例:
定义一个User对象:
package org.example; public class User { private String name ; private Integer age ; public User(){ } public User(String name, Integer age) { this.setName(name); this.setAge(age); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
使用 Comparator.comparing(User::getName) 方法去除重复
package org.example; import com.sun.source.util.Trees; import java.util.ArrayList; import java.util.Comparator; import java.util.TreeSet; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { var list = new ArrayList<User>(); list.add(new User("aa",10)); list.add(new User("aa",15)); list.add(new User("bb",10)); list.add(new User("cc",15)); //根据 name 去除重复 var disList = list.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(Comparator.comparing(User::getName))),ArrayList::new)); for (var item: disList) { System.out.println(item); } } }
结果: