我认为您没有正确理解 Multimap 是什么。 Multimap 从一个或多个键映射到多个值,它是一种 n 到 m 的关系。您似乎拥有的是从 ID 到 Title 的关系,这是一个 n 对 1 的关系。正确的数据结构是 Map,而不是 Multimap。
Map<Integer, String> titlesById = new TreeMap<>(); // keep map ordered by ID
titlesById.put(1, "T1");
titlesById.put(2, "T2");
titlesById.put(3, "T3");
for(Map.Entry<Integer, String> entry : titlesById.entrySet()){
System.out.println("ID : " + entry.getKey() + " Title : " + entry.getValue());
}
这应该会产生所需的输出。
注意:如果您可能通过 ID 从 Map 中查找标题,那么您可能希望从 TreeMap 切换到 HashMap,因为 HashMap 具有恒定时间查找。
更新:显然你确实需要一个 Multimap。然后把上面的代码改成这样:
Multimap<Integer, String> titlesById = TreeMultimap.create<>(); // keep map ordered by ID
titlesById.putAll(1, Arrays.asList("T1a", "T1b", "T1c"));
titlesById.putAll(2, Arrays.asList("T2a", "T2b"));
titlesById.put(3, "T3");
for(Map.Entry<Integer, String> entry : titlesById.entries()){
System.out.println("ID : " + entry.getKey() + " Title : " + entry.getValue());
}
再次重申:TreeMultimap 按键对 Map 进行排序,HashMultimap 具有高效查找功能。
它变得越来越有趣,现在您希望将 3 个值相互连接。在这种情况下,您应该使用Table(3 维地图)。例如
Table<Integer, String, String> titlesAndPlacesById = TreeBasedTable.create();
titlesAndPlacesById.put(1, "T1", "P1");
titlesAndPlacesById.put(2, "T2", "P2");
titlesAndPlacesById.put(3, "T3", "P3");
for(Table.Cell<Integer, String, String> cell : titlesAndPlacesById.cellSet()){
System.out.println("ID : " + cell.getColumnKey() + " Title : " + cell.getRowKey() + ", Place: " + cell.getValue());
}
但这不是一个完美的匹配。如果您想将 ID 映射到标题和地点,那么您可能需要一个自定义对象来封装标题和地点,并将其用作从整数到自定义类型的普通旧 Map 中的值。
public class TitleAndPlace{
private final String title;
private final String place;
TitleAndPlace(String title, String place) {
this.title = title;
this.place = place;
}
public String getTitle() { return title; }
public String getPlace() { return place; }
@Override public boolean equals(Object o) {
if (this == o) return true;
else if (o instanceof TitleAndPlace) {
TitleAndPlace that = (TitleAndPlace) o;
return Objects.equals(title, that.title)
&& Objects.equals(place, that.place);
} else return false;
}
@Override public int hashCode() {
return Objects.hash(title, place);
}
}
Map<Integer, TitleAndPlace> map = new TreeMap<>();
map.put(1, new TitleAndPlace("T1", "P1"));
map.put(2, new TitleAndPlace("T2", "P2"));
for(Map.Entry<Integer, TitleAndPlace> entry : map.entrySet()){
System.out.println("ID : " + entry.getKey() + " Title : " + entry.getValue().getTitle() + ", Place: " + entry.getValue().getPlace());
}