Latest Tutorials| Questions and Answers|Ask Questions?|Site Map




Have Programming Question? Ask it here!
 
 
 


bhaskarreddy
COLLECTIONS12
1 Answer(s)      4 years and 8 months ago
Posted in : Java Interview Questions



Advertisement
View Answers

August 25, 2009 at 10:50 AM


Hi Friend,

Try the following code:

import java.io.*;
import java.util.*;
import java.lang.reflect.*;

class Data{
private int key;
String value;
public Data(){}
public Data(int key, String value) {
super();
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
public String toString(){
return key + " " + value;
}
}
public class ConvertArrayListToHashMap<K> {
public static String put(String str){
if(str != null && (str = str.trim()).length() > 0) {
str = str.substring(0, 1).toUpperCase() + str.substring(1);
}
return str;
}
public static String convertFieldToAccessor(String st) {
return "get" + put(st);
}
public <V> Map<K, V> convertToMap(List<V> list, String keyField) throws Exception {
String accessor = convertFieldToAccessor(keyField);
Map<K, V> map = new HashMap<K, V>();
for(V object : list) {
Method method = object.getClass().getDeclaredMethod(accessor);
K key = (K)method.invoke(object);
map.put(key, object);
}
return map;
}
public static void main(String[] args) throws Exception {
List<Data> list = new ArrayList<Data>();
list.add(new Data(1, "A"));
list.add(new Data(2, "B"));
list.add(new Data(3, "C"));
list.add(new Data(4, "D"));
Map<Long, Data> dimensionMap = new ConvertArrayListToHashMap<Long>().convertToMap(list, "key");
System.out.println(dimensionMap);
}
}

Hope that it will be helpful for you.
Thanks


Related Tutorials/Questions & Answers:
COLLECTIONS12 - Java Interview Questions
COLLECTIONS12  HI i want source code of convert arraylist to hashmap i want key value fairs of each elment in arraylist.Convert Arrraykist to Hashmap.plz send me source code.  Hi Friend, Try the following code
 

 

 

DMCA.com