distinct()是Java8 中 Stream 提供的方法,返回的是由该流中不同元素组成的流。distinct()使用 hashCode() 和 eqauls() 方法来获取不同的元素。因此,需要去重的类必须实现 hashCode() 和 equals() 方法。换句话讲,我们可以通过重写定制的 hashCode() 和 equals() 方法来达到某些特殊需求的去重。 distinct() ...
out.print("distinct去重后:"); out.println(objectMapper.writeValueAsString(studentList));//这里我们将 distinctByKey() 方法作为 filter() 的参数,过滤掉那些不能加入到 set 的元素 studentList =studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList()); out.print("...
@TestpublicvoiddistinctByProperty1()throwsJsonProcessingException {//这里第一种方法我们通过新创建一个只有不同元素列表来实现根据对象某个属性去重ObjectMapper objectMapper =newObjectMapper(); List<Student> studentList =getStudentList(); out.print("去重前 :"); out.println(objectMapper.writeValueAsString(s...
list.stream().filter(distinctByKey(b -> b.getName())); distinctByKey()方法返回一个使用ConcurrentHashMap 来维护先前所见状态的 Predicate 实例,如下是一个完整的使用对象属性来进行去重的示例。 DistinctByProperty.java package com.concretepage; import java.util.ArrayList; import java.util.List; impor...
Java does not have direct support for finding such distinct items from the Stream where items should be distinct by multiple fields. So, we will create a customPredicatefor this purpose. 1. Find Elements Distinct by Multiple Fields Below given is a function that acceptsvarargsparameters and retur...
distinct() 方法声明如下: Streamdistinct(); 1.1 对于 String 列表的去重 因为String 类已经覆写了 equals() 和 hashCode() 方法,所以可以去重成功。 @Test public void listDistinctByStreamDistinct() { // 1. 对于 String 列表去重 ListstringList = new ArrayList() {{ ...
Java Stream distinct by property Sometimes, we want to filter our list on element property or attribute. Below how to perform that : 1 2 3 4 publicstatic<T>Predicate<T>distinctByKey(Function<?superT,Object>keyExtractor){ Map<Object,Boolean>map=newConcurrentHashMap<>(); ...
Streamdistinct() 它是Stream接口的方法。在此示例中,我们有一个包含重复元素的字符串数据类型列表 DistinctSimpleDemo.java package com.concretepage; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class DistinctSimpleDemo { ...
Stream流已经被广泛应用于Java的开发中,本章将简单介绍Stream流的distinct()方法进行对象去重的处理。 去重原理 Stream流中的distinct()去重默认是根据Object中的equals()方法进行去重,而Object中的equals()方法实际为 == 的比较。如果需要对对象进行去重时则需要重写equals和haseCode方法。 案例展示 1.实体类进行改造...
distinct() 方法声明如下: Stream<T> distinct(); 1.1 对于 String 列表的去重 因为String 类已经覆写了 equals() 和 hashCode() 方法,所以可以去重成功。 @Test public void listDistinctByStreamDistinct() { // 1. 对于 String 列表去重 List<String> stringList = new ArrayList<String>() {{ ...