Java 8 Stream的distinct()如何避免长尾词重复问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计455个文字,预计阅读时间需要2分钟。
在Java 8中,使用流操作中的`distinct()`方法无法直接根据对象的某个属性名来去重。`distinct()`方法只能根据对象的引用地址来判断是否重复。为了根据对象的某个属性去重,可以使用`filter()`方法结合一个自定义的`Predicate`来实现。
以下是一个简单的示例,展示如何使用`filter()`和`distinctByKey()`方法来根据对象的某个属性去重:
javaimport java.util.*;import java.util.function.Function;import java.util.function.Predicate;
public class Main { public static void main(String[] args) { List people=Arrays.asList( new Person(Alice, 30), new Person(Bob, 25), new Person(Alice, 30), new Person(Charlie, 35) );
// 使用distinctByKey方法根据name属性去重 List distinctPeople=people.stream() .filter(distinctByKey(Person::getName)) .collect(Collectors.toList());
// 打印结果 distinctPeople.forEach(System.out::println); }
// 自定义distinctByKey方法 public static Predicate distinctByKey(Function keyExtractor) { Map seen=new IdentityHashMap(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE)==null; }
static class Person { private String name; private int age;
public Person(String name, int age) { this.name=name; this.age=age; }
public String getName() { return name; }
public int getAge() { return age; }
@Override public String toString() { return Person{name=' + name + ', age= + age + '}'; } }}
在这个例子中,`distinctByKey()`方法接受一个`Function`作为参数,该函数用于从对象中提取用于去重的键。`IdentityHashMap`用于存储已经看到的键,从而确保只有第一次出现的对象会被保留。这种方法避免了使用额外的`HashMap`,从而减少了内存消耗。
java8 流操作中distinc无法根据对象的某一个属性名来去重,该方法是对distinc的不完善的补充,使用filter来完成,内存上要多消耗一个hashMappublic static
本文共计455个文字,预计阅读时间需要2分钟。
在Java 8中,使用流操作中的`distinct()`方法无法直接根据对象的某个属性名来去重。`distinct()`方法只能根据对象的引用地址来判断是否重复。为了根据对象的某个属性去重,可以使用`filter()`方法结合一个自定义的`Predicate`来实现。
以下是一个简单的示例,展示如何使用`filter()`和`distinctByKey()`方法来根据对象的某个属性去重:
javaimport java.util.*;import java.util.function.Function;import java.util.function.Predicate;
public class Main { public static void main(String[] args) { List people=Arrays.asList( new Person(Alice, 30), new Person(Bob, 25), new Person(Alice, 30), new Person(Charlie, 35) );
// 使用distinctByKey方法根据name属性去重 List distinctPeople=people.stream() .filter(distinctByKey(Person::getName)) .collect(Collectors.toList());
// 打印结果 distinctPeople.forEach(System.out::println); }
// 自定义distinctByKey方法 public static Predicate distinctByKey(Function keyExtractor) { Map seen=new IdentityHashMap(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE)==null; }
static class Person { private String name; private int age;
public Person(String name, int age) { this.name=name; this.age=age; }
public String getName() { return name; }
public int getAge() { return age; }
@Override public String toString() { return Person{name=' + name + ', age= + age + '}'; } }}
在这个例子中,`distinctByKey()`方法接受一个`Function`作为参数,该函数用于从对象中提取用于去重的键。`IdentityHashMap`用于存储已经看到的键,从而确保只有第一次出现的对象会被保留。这种方法避免了使用额外的`HashMap`,从而减少了内存消耗。
java8 流操作中distinc无法根据对象的某一个属性名来去重,该方法是对distinc的不完善的补充,使用filter来完成,内存上要多消耗一个hashMappublic static

