UtilCollection.java 1.62 KB
package com.taover.util;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UtilCollection{
	
	 public static Map<String, ?> listToMap(List<?> elements, String keyFieldName){
		Map<String, Object> result = new HashMap<String, Object>();
		if(elements==null || keyFieldName==null || keyFieldName.isEmpty()){
			return null;
		}
		for(int i=0; i<elements.size(); ++i){
			Object tempObject = elements.get(i);
			try {
				Field tempField = tempObject.getClass().getDeclaredField(keyFieldName);
				tempField.setAccessible(true);
				Object tempValue = tempField.get(tempObject);
				if(tempValue == null){
					result.put(null, tempObject);					
				}else{
					result.put(tempValue.toString(), tempObject);
				}
			} catch (Exception e) {				
				continue;
			}
		}
		return result;
	}
	
	public static String getStringFromRequestParamMap(Map<String, ?> data, String key){
		if(data == null){
			return null;
		}
		Object value = data.get(key);
		if(value == null){
			return null;
		}else{
			if(value.getClass().isArray()){
				return String.valueOf(Array.get(value, 0));
			}else{
				return String.valueOf(value);
			}
		}
	}
	 
	public static void main(String args[]){
		List<TestColl> data = new ArrayList<TestColl>();		
		data.add(new TestColl("1","2"));
		data.add(new TestColl("3","4"));
		data.add(new TestColl("5","6"));
		Map temp = UtilCollection.listToMap(data, "a");
		System.out.println(temp.get("1"));
	}
}

class TestColl {
	String a;
	String b;
	public TestColl(String a, String b){
		this.a = a;
		this.b = b;
	}
}