双人课:import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Main2 { public static void main(String[] args) { // input ArrayList<Pair> pairs = new ArrayList<Pair>(); pairs.add(new Pair( "H" , "G")); pairs.add(new Pair( "F" , "G")); pairs.add(new Pair( "G" , "D")); // ... // Arrange // String corresponds to the Id Map<String, MegaMenuDTO> hm = new HashMap<>(); // you are using MegaMenuDTO as linked list with next and before link // populate a Map for(Pair p:pairs){ // ----- Child ----- MegaMenuDTO mmdChild ; if(hm.containsKey(p.getChildId())){ mmdChild = hm.get(p.getChildId()); } else{ mmdChild = new MegaMenuDTO(); hm.put(p.getChildId(),mmdChild); } mmdChild.setId(p.getChildId()); mmdChild.setParentId(p.getParentId()); // no need to set ChildrenItems list because the constructor created a new empty list // ------ Parent ---- MegaMenuDTO mmdParent ; if(hm.containsKey(p.getParentId())){ mmdParent = hm.get(p.getParentId()); } else{ mmdParent = new MegaMenuDTO(); hm.put(p.getParentId(),mmdParent); } mmdParent.setId(p.getParentId()); mmdParent.setParentId("null"); mmdParent.addChildrenItem(mmdChild); } // Get the root List<MegaMenuDTO> DX = new ArrayList<MegaMenuDTO>(); for(MegaMenuDTO mmd : hm.values()){ if(mmd.getParentId().equals("null")) DX.add(mmd); } // Print for(MegaMenuDTO mmd: DX){ System.out.println("DX contains "+DX.size()+" that are : "+ mmd); } }}
MegaMenuDTO类已更新public class Pair { private String childId ; private String parentId; public Pair(String childId, String parentId) { this.childId = childId; this.parentId = parentId; } public String getChildId() { return childId; } public void setChildId(String childId) { this.childId = childId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; }}
import java.util.ArrayList;import java.util.List;public class MegaMenuDTO { private String Id; private String name; private String parentId; private List<MegaMenuDTO> childrenItems; public MegaMenuDTO() { this.Id = ""; this.name = ""; this.parentId = ""; this.childrenItems = new ArrayList<MegaMenuDTO>(); } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public List<MegaMenuDTO> getChildrenItems() { return childrenItems; } public void setChildrenItems(List<MegaMenuDTO> childrenItems) { this.childrenItems = childrenItems; } public void addChildrenItem(MegaMenuDTO childrenItem){ if(!this.childrenItems.contains(childrenItem)) this.childrenItems.add(childrenItem); } @Override public String toString() { return "MegaMenuDTO [Id=" + Id + ", name=" + name + ", parentId=" + parentId + ", childrenItems=" + childrenItems + "]"; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)