将A,B两个自定义对象类型的List合并为一个Map,其中集合A作为key,集合B作为value,提供java代码
时间: 2023-10-06 15:05:13 浏览: 80
下面是一个简单的Java代码示例,将两个自定义对象类型的List合并为一个Map,其中集合A作为key,集合B作为value:
```java
import java.util.*;
public class MergeListsToMap {
public static void main(String[] args) {
// Create two custom object type lists
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 25));
personList.add(new Person("Bob", 30));
List<Address> addressList = new ArrayList<>();
addressList.add(new Address("123 Main St", "Anytown", "USA"));
addressList.add(new Address("456 Elm St", "Othertown", "USA"));
// Merge the lists into a map
Map<List<Person>, List<Address>> map = new HashMap<>();
map.put(personList, addressList);
// Print out the map
System.out.println(map);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Address {
private String street;
private String city;
private String country;
public Address(String street, String city, String country) {
this.street = street;
this.city = city;
this.country = country;
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
}
```
在这个示例中,我们创建了两个自定义对象类型的List,一个是Person对象的列表,另一个是Address对象的列表。我们使用HashMap将这两个列表合并为一个Map,其中Person列表作为键,Address列表作为值。最后,我们打印出这个Map来验证它是否正确合并了两个列表。
阅读全文