Stream去重整理


分兩部分整理:

 https://juejin.cn/post/6844903842132262926

  • 基於Stream中對象去重

 

1. Stream 的distinct()方法

distinct()是Java 8 中 Stream 提供的方法,返回的是由該流中不同元素組成的流。distinct()使用 hashCode()eqauls() 方法來獲取不同的元素。因此,需要去重的類必須實現 hashCode()equals() 方法。換句話講,我們可以通過重寫定制的 hashCode()equals() 方法來達到某些特殊需求的去重。

@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

 

  • 基於Stream對象屬性屬性

 

  @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));
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM