首頁  >  文章  >  Java  >  如何使用Java 8的Stream實作清單去重?

如何使用Java 8的Stream實作清單去重?

WBOY
WBOY轉載
2023-05-08 11:07:142061瀏覽

一. Stream 的distinct()方法

distinct()是Java 8 中 Stream 提供的方法,傳回的是由此流中不同元素所組成的流。 distinct()使用 hashCode() 和 eqauls() 方法來取得不同的元素。

因此,需要去重的類別必須實作 hashCode() 和 equals() 方法。換句話說,我們可以透過重寫客製化的 hashCode() 和 equals() 方法來達到某些特殊需求的去重。

distinct() 方法宣告如下:

Stream<T> distinct();

1.1 對於String 清單的去重

因為String 類別已經覆寫了equals() 和hashCode() 方法,所以可以去重成功。

@Test
public void listDistinctByStreamDistinct() {
  // 1. 对于 String 列表去重
  List<String> stringList = new ArrayList<String>() {{
    add("A");
    add("A");
    add("B");
    add("B");
    add("C");
  }};
  out.print("去重前:");
  for (String s : stringList) {
    out.print(s);
  }
  out.println();
  stringList = stringList.stream().distinct().collect(Collectors.toList());
  out.print("去重后:");
  for (String s : stringList) {
    out.print(s);
  }
  out.println();

}

結果如下:

去重前:AABBC
去重後:ABC

1.2 對於實體類別清單的去重

附註:程式碼中我們使用了Lombok 外掛程式的@Data註解,可自動覆寫equals() 以及hashCode() 方法。

/**
* 定义一个实体类
*/  
@Data
public class Student {
  private String stuNo;
  private String name;
}
@Test
public void listDistinctByStreamDistinct() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    // 1. 对于 Student 列表去重
    List<Student> studentList = getStudentList();
    out.print("去重前:");
    out.println(objectMapper.writeValueAsString(studentList));
    studentList = studentList.stream().distinct().collect(Collectors.toList());
    out.print("去重后:");
    out.println(objectMapper.writeValueAsString(studentList));
  }

結果如下:

去重前:[{"stuNo":"001","name":"Tom"},{"stuNo":"002" ,"name":"Mike"},{"stuNo":"001","name":"Tom"}]
去重後:[{"stuNo":"001","name":" Tom"},{"stuNo":"002","name":"Mike"}]

#二. 根據Lista87fdacec66f0909fc0757c19f2d2b1d 中Object 某個屬性去重

#2.1 新建一個清單出來

@Test
  public void distinctByProperty1() throws JsonProcessingException {
    // 这里第一种方法我们通过新创建一个只有不同元素列表来实现根据对象某个属性去重
    ObjectMapper objectMapper = new ObjectMapper();
    List<Student> studentList = getStudentList();
    out.print("去重前        :");
    out.println(objectMapper.writeValueAsString(studentList));
    studentList = studentList.stream().distinct().collect(Collectors.toList());
    out.print("distinct去重后:");
    out.println(objectMapper.writeValueAsString(studentList));
    // 这里我们引入了两个静态方法,以及通过 TreeSet<> 来达到获取不同元素的效果
    // 1. import static java.util.stream.Collectors.collectingAndThen;
    // 2. import static java.util.stream.Collectors.toCollection;
    studentList = studentList.stream().collect(
      collectingAndThen(
        toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new)
    );
    out.print("根据名字去重后 :");
    out.println(objectMapper.writeValueAsString(studentList));
  }

結果如下:

去重前       :[{"stuNo":"001","name":"Tom"},{" stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
distinct去重後:[{"stuNo":"001 ","name":"Tom"},{"stuNo":"003","name":"Tom"}]
依照名字去重後:[{"stuNo":"001","name ":"Tom"}]

2.2 透過filter() 方法

#我們先建立一個方法作為Stream.filter() 的參數,其傳回類型為Predicate,原理就是判斷一個元素能否加入Set 去,程式碼如下:

private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}

使用如下:

@Test
  public void distinctByProperty2() throws JsonProcessingException {
    // 这里第二种方法我们通过过滤来实现根据对象某个属性去重
    ObjectMapper objectMapper = new ObjectMapper();
    List<Student> studentList = getStudentList();
    out.print("去重前        :");
    out.println(objectMapper.writeValueAsString(studentList));
    studentList = studentList.stream().distinct().collect(Collectors.toList());
    out.print("distinct去重后:");
    out.println(objectMapper.writeValueAsString(studentList));
    // 这里我们将 distinctByKey() 方法作为 filter() 的参数,过滤掉那些不能加入到 set 的元素
    studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());
    out.print("根据名字去重后 :");
    out.println(objectMapper.writeValueAsString(studentList));
  }

結果如下:

##去重前       :[{" stuNo":"001","name":"Tom"},{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom" }]

distinct去重後:[{"stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
依名字去重後:[{"stuNo":"001","name":"Tom"}]

以上是如何使用Java 8的Stream實作清單去重?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除