import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 类List4Map.java的实现描述:List4Map.java
*
* @author ahhqcheng 2012-2-29 下午7:56:11
*/
public class List4Map {
/**
* @description 实现将一个List转化为Map<Key,List>的样式
* @param 某个对象的List
* @return Map<Key,List>
*/
public Map<Integer, List<TestObject>> list4Map(List<TestObject> list) {
Map<Integer, List<TestObject>> map = new HashMap<Integer, List<TestObject>>();
if ((list != null) && (list.size() != 0)) {
for (TestObject test : list) {
// 这一步是关键,也很巧妙吧,哈哈
List<TestObject> testList = map.get(test.getId());
if (testList == null) {
testList = new ArrayList<TestObject>();
}
testList.add(test);
map.put(test.getId(), testList);
}
}
return map;
}
/**
* @description 对Map<key,List>的数据结构进行遍历
* @param Map<key,List>
* @return void
*/
public void outOfMap(Map<Integer, List<TestObject>> map) {
Set<Integer> keySet = map.keySet();
for (Iterator<Integer> i = keySet.iterator(); i.hasNext();) {
Integer key = i.next();
System.out.println(key + " : ");
List<TestObject> testList = map.get(key);
for (TestObject test : testList) {
System.out.print("<--" + test.getName() + "--" + test.getAddress() + "-->");
}
System.out.println();
}
}
public static void main(String[] args) {
List4Map list4Map = new List4Map();
/**
* 构造数据
*/
List<TestObject> list = new ArrayList<TestObject>();
TestObject test1 = list4Map.new TestObject(1, "name1", "address1");
TestObject test2 = list4Map.new TestObject(1, "name2", "address2");
TestObject test3 = list4Map.new TestObject(1, "name3", "address3");
TestObject test4 = list4Map.new TestObject(2, "name1", "address1");
TestObject test5 = list4Map.new TestObject(2, "name2", "address2");
TestObject test6 = list4Map.new TestObject(2, "name3", "address3");
list.add(test1);
list.add(test2);
list.add(test3);
list.add(test4);
list.add(test5);
list.add(test6);
// 装换
Map<Integer, List<TestObject>> map = new HashMap<Integer, List<TestObject>>();
map = list4Map.list4Map(list);
// 输出
list4Map.outOfMap(map);
}
class TestObject {
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public TestObject(int id, String name, String address){
this.id = id;
this.name = name;
this.address = address;
}
public TestObject(){
}
}
}
实现将一个List转化为Map<Key,List>的样式
最新推荐文章于 2024-07-13 03:07:40 发布