[英]How can I put many objects in a Map with the same parameter name
I have this code but it seems to over write one parameter and I only end up with one myImages
parameter no matter how many values i have in imagesList
我有这个代码,但它似乎过度编写一个参数,我最终只得到一个myImages
参数,无论我在imagesList
有多少个值
Is there a way to put the put many objects in a Map with the same name? 有没有办法将许多对象放在具有相同名称的Map中?
for(String imagePath: imagesList){
File imageFile = new File(imagePath);
params.put("myImages", imageFile);
}
edit I must use a map since a library that i am using to make multipart POST requests requires that i put the file in a map 编辑我必须使用地图,因为我用来制作多部分POST请求的库要求我将文件放在地图中
You need to use a collection as the Map
value. 您需要使用集合作为Map
值。
A Map
stores a unique key -> value mapping so putting the same value again simply overwrites it. Map
存储唯一键 - >值映射,因此再次放置相同的值只会覆盖它。 You can either use a Map<String, Collection<File>>
like so: 您可以使用Map<String, Collection<File>>
如下所示:
final Map<String, Collection<File>> myMap = new HashMap<String, Collection<File>>();
//...
Collection<File> files = myMap.get("myImages");
if(files == null) {
files = new LinkedList<File>();
myMap.put("myImages", files);
}
for(String imagePath: imagesList){
File imageFile = new File(imagePath);
files.add(imageFile);
}
Or you could consider using a Multimap
implementation from the likes of Guava . 或者您可以考虑使用Guava之类的Multimap
实现。
As others have mentioned use Guava's Multimap
, it allows you to associate many values against a single key, for example: 正如其他人提到的那样,使用Guava的Multimap
,它允许您将多个值与单个键相关联,例如:
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("myImages", file1);
multimap.put("myImages", file2);
multimap.put("myImages", file3);
Collection<File> images = multimap.get("myImages");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.