java 集合转map实现自定义key
时间: 2023-09-14 07:08:39 浏览: 91
Java集合可以通过使用Map接口来实现自定义Key。以下是一些示例代码:
1. 使用HashMap实现自定义Key
```
Map<Person, String> map = new HashMap<>();
Person p1 = new Person("Tom", 25);
Person p2 = new Person("Jerry", 30);
map.put(p1, "Tom's value");
map.put(p2, "Jerry's value");
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//重写hashCode和equals方法
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
```
2. 使用TreeMap实现自定义Key,并按照Key排序
```
Map<Person, String> map = new TreeMap<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int result = o1.getName().compareTo(o2.getName());
if (result == 0) {
result = o1.getAge() - o2.getAge();
}
return result;
}
});
Person p1 = new Person("Tom", 25);
Person p2 = new Person("Jerry", 30);
map.put(p1, "Tom's value");
map.put(p2, "Jerry's value");
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//getter方法和重写hashCode和equals方法
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
```
在使用TreeMap实现自定义Key时,需要实现一个Comparator接口,该接口用于比较两个对象的大小。在该例中,按照姓名升序排序,如果姓名相同,则按照年龄升序排序。
阅读全文