从Map中检索值<list>并将每个值存储在String变量</list>中

时间:2011-11-15 11:59:29

标签: java

我无法将List<String>的{​​{1}}值转换为Map

源代码如下:

String

此代码无效。

请告诉我,我如何将这些值转换为String。

4 个答案:

答案 0 :(得分:1)

您缺少argValue数组的实例化。

Map<String ,List<String>> profileFields)
String argValue[] = null;
int loopCounter = 0;

Object[] obj = profileFields.values().toArray();

argValue = new String[obj.length];

for(int i = 0 ; i < obj.length ; i++){
    System.out.println("Values####"+obj[i]);
    argValue[loopCounter] = (String) obj[i];
 }

答案 1 :(得分:1)

您的数组是List<String>的数组。

Object[] obj = profileFields.values().toArray();

实际上是

List<String>[] obj = profileFields.values().toArray();

因为values正在返回List个对象的集合。

考虑使用实现Map Lists的番石榴ListMultimap

答案 2 :(得分:0)

你忘了初始化argValue:

String argValue[] = new String[ profileFields.values().size() ];

loopCounter不会增加resue i或loopCounter ++

这样可行:

ArrayList<String> allLists = new ArrayList<String>();
for ( List<String> list : profileFields.values() ) {
    allLists.addAll( list );
}
String[] argValue = new String[ allLists.size() ];

for ( int i = 0 ; i < argValue.length ; i++ ) {
    argValue[i] = allLists.get( i );
    System.out.println( "Values####" + argValue[i] );
}

编辑:

您还可以通过

替换最后一个循环(不打印)
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class); 

答案 3 :(得分:0)

Map<String, List<String>> profileFields = new HashMap<String, List<String>>();
        profileFields.put("s1", new ArrayList<String>() {
            {
                add("l11");
                add("l12");
            }
        });
        profileFields.put("s2", new ArrayList<String>() {
            {
                add("l21");
                add("l22");
            }
        });

        List<String> argValue[] = null;
        int loopCounter = 0;

        //this will get you an array of elements, each element representing a Map value
        //your map Values are if type List<String>, so you'll get an array of Lists
        Object[] obj = profileFields.values().toArray();
        for(int i = 0 ; i < obj.length ; i++){
            System.out.println("Values####"+obj[i]);
            argValue[loopCounter] = (List<String>) obj[i];
         }