【发布时间】: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