UtilCollection.java
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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;
}
}