墨色风雨
首先声明这个答案一下纯属娱乐,从实用角度来说毫无益处。但是确实完全满足了生成map的时候没有for循环。至于使用map的时候嘛……
public class MapTest {
@Test
public void testMakeMap() throws Exception {
String[] cols = "name,age,gender,phone".split(",", -1);
String[] message = "abc\tdef\t123\t456".split("\\t", -1);
Map map = toMap(cols, message);
assertThat(map.get("name"), is("abc"));
assertThat(map.get("phone"), is("456"));
assertThat(map.get("age"), is("def"));
assertThat(map.get("gender"), is("123"));
}
private Map toMap(String[] keys, String[] values) {
return new AbstractMap(){
public Set> entrySet() {
return new AbstractSet>() {
public int size() {
return keys.length;
}
public Iterator> iterator() {
return new Iterator>(){
int i = 0;
public boolean hasNext() {
return i < keys.length;
}
public Entry next() {
int current = i++;
return new Entry() {
public String getKey() {
return keys[current];
}
public String getValue() {
return values[current];
}
public String setValue(String s) {
throw new UnsupportedOperationException();
}
};
}
};
}
};
}
};
}
}