2013年11月19日星期二

Help on the list into question

map There are four string array

s1 = {0,1}

s2 = {0,2}

s3 = {1,1}

s4 = {1,2}

list = {s1, s2, s3, s4}

now want to list the string in the first element of the array into the same map the key value , the second element of the array on the string to form a new array of values ​​as a value .

The resulting map is

map = {key = 0 value = {1,2}, key = 1 value = {1,2}}
hope god more help.



------ Solution ------------------------------------ --------

public static void testMap() {

List<String[]> list = createDatas();
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String[] arr : list) {
if (2 < arr.length) {
throw new IllegalArgumentException("out of index");
}
String a = arr[0];
String b = arr[1];
if (!map.containsKey(a)) {
List<String> tmpList = new ArrayList<String>();
tmpList.add(b);
map.put(a, tmpList);
} else {
map.get(a).add(b);
}
}

Iterator<Entry<String, List<String>>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, List<String>> entry = it.next();
System.out.println(entry);
}
// ========= output=========
// 1=[1, 2, 2, 2]
// 0=[1, 2]

}

private static List<String[]> createDatas() {
String[] s1 = { "0", "1" };

String[] s2 = { "0", "2" };

String[] s3 = { "1", "1" };

String[] s4 = { "1", "2" };
String[] s5 = { "1", "2" };
String[] s6 = { "1", "2" };
List<String[]> list = new ArrayList<String[]>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
return list;
}

------ For reference only ------------------------ ---------------


brother, you are given the code of Java it ? Inside the IDE to write your code above is not being given ? First good tidy your code, and then sent to the questions.
------ For reference only -------------------------------------- -

  
brother, you are given the code of Java it ? Inside the IDE to write your code above does not   
  
  
  
error ? First good tidy your code, and then sent to the questions. [ /   
quote]   
  
  
The actual algorithm is much more complicated than I, for example , I just use a simple example , let us think about how to help me achieve .  
------ For reference only ---------------------------------- -----





2 Floor Hello , thank you for your reply , but I have a question .

I try your method

------ For reference only -------------- -------------------------
2 floor is right, the key issue is to use a list mounted behind the string, thank you.

没有评论:

发表评论