我有一个名单,需要转换为所有具有相同姓氏的人都被标记的结果。例如:
来源列表:
JayReese
ClaraSmith
JohnSmith
输出:
JayReese
ClaraSmith1
JohnSmith2
Person
类的代码写在下面,如何比较所有lastName
,并且当有重复的lastName
时,为每个添加唯一索引?应该添加什么方法?
我非常感谢任何意见和/或帮助。非常感谢。
import java.util.*;
public class Person implements Comparable<Person> {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString() {
return lastName + firstName;
}
}
最佳答案
首先,编辑 Person
类或创建一个具有可设置索引字段的新类。对于您的用例来说,可比性是完全没有必要的。
public class Person {
private String firstName;
private String lastName;
public int index;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString() {
return lastName + firstName + (index != 0 ? index : "");
}
}
您可以使用 HashMap<String, Integer>
将编号添加到姓氏中,如下所示:
public static void numberDuplicateLastNames(List<Person> people) {
HashMap<String, Integer> duplicatedLastNames = new HashMap<>();
for(Person p : people) {
if(! duplicatedLastNames.containsKey(p.lastName)) {
duplicatedLastNames.put(p.lastName, 1);
p.index = 1;
} else {
int i = duplicatedLastNames.get(p.lastName) + 1;
duplicatedLastNames.put(p.lastName, i);
p.index = i;
}
}
//Remove index from the people who don't have a duplicate last name
for(Person p : people) {
if (duplicatedLastNames.get(p.lastName) == 1) {
p.index = 0;
}
}
}
关于java - 如何标记重复的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576514/