【问题标题】:Appending a string when find duplicate using stream使用流查找重复项时附加字符串
【发布时间】:2020-08-18 13:35:58
【问题描述】:

我确实有一个用例,我需要在模型层中附加一个带有版本(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", "abc" , "xyz_a3"}
        }
}

【问题讨论】:

    标签: java list java-8 java-stream


    【解决方案1】:

    使用您之前的问题列表.. 下面应该会给您想要的结果 -

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

    【讨论】:

    • 是的,这行得通。错过了这可以在 Map 本身而不是 FlatMap 中完成。谢谢
    【解决方案2】:

    在您的班级中覆盖equalshashCode 是个好主意。如果您这样做是为了比较 name 字段,则不需要 Set 来收集重复项。你可以这样做:

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

    打印

    xyz_a1
    abc
    xyz_a3
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多