Appending a string when find duplicate using stream

Tags: , , ,

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.

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

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>();
            //Get only names from the list
   -> l2.add(e.getName()));
            // Output is
            //Finding only the duplicate ones
            Set<String> result = -> Collections.frequency(l2, i) > 1).collect(Collectors.toSet());
            //Output is
            //Not sure how to proceed from here
   -> e.getName()).flatMap(x -> result.contains(x) ? Stream.of(x + ))
            //expected output
            //{"xyz_a1", "abc" , "xyz_a3"}


using your previous lists from your question.. below should give you desire result –
  .map(e -> result.contains(e.getName())? String.join("_",e.getName(),e.getValue()) : e.getName())

Source: stackoverflow