使用流查找重复项时追加字符串

问题描述

我确实有一个用例,我需要在模型层中附加一个带有版本(name_version)的字符串(名称)。但这仅适用于列表中重复的名称

Student.java

private class Student{
        private String name;
        private String value;
}

Test.java

public class NewTes {
    public static void main(String[] args){
            
            Student s1 = new Student("xyz","a1");
            Student s2 = new Student("abc","a2");
            Student s3 = new Student("xyz","a3");
            List<String> l2 = new ArrayList<>();
            List<Student> l1 = new ArrayList<Student>();
            l1.add(s1);
            l1.add(s2);
            l1.add(s3);
            
            //Get only names from the list
            l1.stream().forEach(e -> l2.add(e.getName()));
            
            // Output is
            //{"xyz","abc","xyz"}
    
            //Finding only the duplicate ones
            Set<String> result = l2.stream().filter(i -> Collections.frequency(l2,i) > 1).collect(Collectors.toSet());
            
            //Output is
            //{"xyz"}
            
            //Not sure how to proceed from here
            l1.stream().map(e -> e.getName()).flatMap(x -> result.contains(x) ? Stream.of(x + ))
            
            //expected output
            //{"xyz_a1","xyz_a3"}
        }
}

解决方法

使用问题中的先前列表。.下面应该会为您提供所需的结果-

l1.stream()
  .map(e -> result.contains(e.getName())? String.join("_",e.getName(),e.getValue()) : e.getName())
  .collect(Collectors.toList());
,

在您的课程中重写equalshashCode是一个好主意。如果您这样做是为了在name字段上进行比较,则不需要Set来收集重复项。您可以按照以下步骤进行操作:

List<String> list = l1.stream()
        .map(e -> Collections.frequency(l1,e) > 1 ?
                String.join("_",e.getValue()) :
                e.getName())
        .collect(Collectors.toList());

list.forEach(System.out::println);

打印

xyz_a1
abc
xyz_a3