![](/img/trans.png)
[英]How to Convert Stream Stream<HashMap<String, Object>> to HashMap Array HashMap<String, Object>[]?
[英]String Array Into HashMap Collection Object
我有以下
String[] temp;
哪个返回
red
blue
green
我想将字符串数组添加到像HashMap这样的集合对象中,以便可以检索任何类中的值,例如
HashMap hash = New HashMap();
hash.get("red");
hash.get("blue");
hash.get("green");
我怎样才能做到这一点?
谢谢
更新1
String str = "red,blue,green";
String[] temp;
String delimiter = ",";
temp = str.split(delimiter);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
通过上面的代码,我想基于数组中的值检索值。 例如,我想通过调用hash.get(“ One”)从另一个类中获取值,该对象将返回红色,hash.get(“ Two”)将返回蓝色,依此类推。
Map<String, String> hash = new HashMap<String, String>();
for(i = 0 ; i < temp.length(); i++)
{
hash.put(temp[i], temp[i]);
}
然后,您可以从地图hash.get(temp [i]);中检索。
HashMap<String, String>() map = new HashMap<String, String>();
map.put(temp[i], temp[i]);//here i have considered key as the value itself.. u can use something else //also.
我怀疑如何将temp [i]映射为红色,蓝色或绿色?
使用哈希图不能直接解决此问题。 目前您需要写
temp[ someNumberHere ];
所以
temp[ 1 ];
产生一个字符串“ blue”
如果您有hashMap,则可以编写
myColourMap.get( someNumberHere );
所以
myColourMap.get( 1 );
会产生“蓝色”。 无论哪种情况,您都将一个值转换为相应的字符串,但是您确实需要知道“ someNumber”。 如果要“蓝色”,则需要知道要输入数字1。
可能您需要的是使用命名良好的常量值:
public Class Colours {
public static final int RED = 0;
public static final int BLUE = 1;
public static final int GREEN = 1;
// plus either the array of strings or the hashMap
public statuc String getColour(int colourNumber ) {
return myArray[colourNumber]; // or myMap.get(colourNumber)
}
}
您的客户现在可以编写如下代码
Colours.getColour( Colour.RED );
[使用枚举比仅使用原始int更好,但现在不让我们从数组和hashMap转移过来]。
现在什么时候可以使用hashMap而不是数组? 考虑您可能有更多的颜色,例如12695295可能是“浅粉红色”,而16443110可能是“淡紫色”。
现在,当您仅使用其中的500个条目时,您实际上就不希望有一个包含16,443,110个条目的数组。 现在,HashMap真的很有用
myMap.put( Colour.LAVENDER, 16443110 );
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.