日期:2014-05-20 浏览次数:20776 次
import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class StudyMap { public static void main(String[] args) { HashMap<Integer, List<OKBean>> result = new HashMap<Integer, List<OKBean>>(); List<OKBean> testList = new ArrayList<OKBean>(); testList.add(new OKBean(1, 0)); testList.add(new OKBean(2, 0)); testList.add(new OKBean(3, 0)); testList.add(new OKBean(4, 1)); testList.add(new OKBean(5, 1)); testList.add(new OKBean(6, 1)); testList.add(new OKBean(7, 2)); testList.add(new OKBean(8, 2)); testList.add(new OKBean(9, 2)); testList.add(new OKBean(10, 4)); testList.add(new OKBean(11, 4)); testList.add(new OKBean(12, 4)); for (OKBean okbean : testList) { List<OKBean> okbeans = result.get(okbean.getParentId()); if (okbeans == null) { okbeans = new ArrayList<OKBean>(); result.put(okbean.getParentId(), okbeans); } okbeans.add(okbean); } displayMap(result, 1, ""); } public static void displayMap(HashMap<Integer, List<OKBean>> result, int startKey, String str) { List<OKBean> list = result.get(startKey); for (OKBean okBean : list) { System.out.println(str + okBean.getId() + ":"); if (result.containsKey(okBean.getId())) { displayMap(result, okBean.getId(), str + " "); } } } } class OKBean { public OKBean() { } public OKBean(int id, int parentId) { this.id = id; this.parentId = parentId; } private int id; private int parentId; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } }