首先定义一个实体类Person, 两个属性编号和姓名.
class Person {
public Person(int id, String name) {
this.id = id;
this.name = name;
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
然后给person数组赋值,这里我故意写了几个重复数据。
private static final List<Person> persons = new ArrayList<Person>() {{
add(new Person(1, "zhangsan1"));
add(new Person(2, "zhangsan2"));
add(new Person(3, "zhangsan3"));
add(new Person(4, "zhangsan4"));
add(new Person(1, "zhangsan1"));
add(new Person(4, "zhangsan4"));
add(new Person(3, "zhangsan3"));
add(new Person(4, "zhangsan4"));
}};
最后在Main函数里对List数组进行去重处理
public static void main(String[] args) {
Map<Person, List<Integer>> indexes = new HashMap<>();
for (int i = 0; i < persons.size(); i++) {
indexes.computeIfAbsent(persons.get(i), c -> new ArrayList<>()).add(i);
}
System.out.println(indexes);
}
运行结果
{Person{id=4, name='zhangsan4'}=[3, 5, 7], Person{id=3, name='zhangsan3'}=[2, 6], Person{id=2, name='zhangsan2'}=[1], Person{id=1, name='zhangsan1'}=[0, 4]}
网友评论