用 Java 实现一对多映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6005617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:57:05  来源:igfitidea点击:

Implementing a one to many map in Java

javadata-structures

提问by algorithmicCoder

Have one objectof type Athat is related to a bunch of objectsof type Band want to store all objectsof type Aand easily access their type Brelations.

有一个objecttype A被涉及到一堆objectstype B,想存储所有objectstype A地访问他们的type B关系。

What's the best (built-in?) data structure doing this in Java?

在 Java 中执行此操作的最佳(内置?)数据结构是什么?

回答by Zach L

You could have a Mapof type Aobjects to a Listor Set(or whichever Collectionworks best) of type Bobjects, like:

你可以有一个地图type A对象添加到列表(或任何类别的最好)的type B对象,如:

 Map<A,List<B>> map = new HashMap<A,List<B>>();

Or use Google's MultiMapinterface, which will do essentially the same as above, but with less work on your part.

或者使用 Google 的MultiMap界面,它的作用与上述基本相同,但您的工作较少。