>  기사  >  Java  >  Java 8의 Stream을 사용하여 목록 중복 제거를 구현하는 방법은 무엇입니까?

Java 8의 Stream을 사용하여 목록 중복 제거를 구현하는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-05-08 11:07:142063검색

1. Stream

distinct()의 independent() 메소드는 Java 8의 Stream에서 제공하는 메소드입니다. 스트림의 다양한 요소로 구성된 스트림을 반환합니다. independent()는 hashCode() 및 eqauls() 메서드를 사용하여 고유한 요소를 가져옵니다.

따라서 중복 제거가 필요한 클래스는 hashCode() 및 equals() 메서드를 구현해야 합니다. 즉, 사용자 정의된 hashCode() 및 equals() 메서드를 재정의하여 특정 특별한 요구 사항을 충족할 수 있습니다.

distinct() 메서드는 다음과 같이 선언됩니다.

Stream<T> distinct();

1.1 문자열 목록 중복 제거의 경우

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 주석을 사용합니다. 자동으로 덮어쓸 수 있는 in입니다. 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"}]

2. Lista87fdacec66f0909fc0757c19f2d2b1d

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" }]
별도의 중복 제거 후: [{"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","이름" :"Tom"},{"stuNo":"001","name":"Tom"},{"stuNo":"003","name": "Tom"}]
중복 항목을 제거한 후 구별됨:[{ "stuNo":"001","name":"Tom"},{"stuNo":"003","name":"Tom"}]
After 이름을 기준으로 중복 제거: [{"stuNo":"001 ","name":"Tom"}]

위 내용은 Java 8의 Stream을 사용하여 목록 중복 제거를 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제