Skip to content
Advertisement

Appending a string when find duplicate using stream

I do have a use case where i need to append a string(name) with version (name_version) which i will have in a model layer. But this is to be done only for the name which are duplicate in the list.

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"}
        }
}

Advertisement

Answer

using your previous lists from your question.. below should give you desire result –

l1.stream()
  .map(e -> result.contains(e.getName())? String.join("_",e.getName(),e.getValue()) : e.getName())
  .collect(Collectors.toList());
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement