如何解决使用流查找重复项时追加字符串
我确实有一个用例,我需要在模型层中附加一个带有版本(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());
,
在您的课程中重写equals
和hashCode
是一个好主意。如果您这样做是为了在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。