package com.test; /** * @author * @description TODO * @date 2019/6/29 */ public class Label { private String name; private String code; private String parCode; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getParCode() { return parCode; } public void setParCode(String parCode) { this.parCode = parCode; } public Label(String name, String code, String parCode) { this.name = name; this.code = code; this.parCode = parCode; } }
package com.test; import java.util.List; /** * @author * @description TODO * @date 2019/6/29 */ public class LabelData { private String name; private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } private List<LabelData> children; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<LabelData> getChildren() { return children; } public void setChildren(List<LabelData> children) { this.children = children; } public LabelData(String code, String name) { this.name = name; this.code = code; } }
package com.test; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author * @description TODO * @date 2019/6/29 */ public class TestChildren { public static void main(String[] args) { List<LabelData> result = new ArrayList<>(); List<Label> labelList = new ArrayList<>(); labelList.add(new Label("食物","all", null)); labelList.add(new Label("水果","fruits","all")); labelList.add(new Label("苹果","apple","fruits")); labelList.add(new Label("梨","pear","fruits")); labelList.add(new Label("蔬菜","vegetables","all")); labelList.add(new Label("西红柿","tomatoes","vegetables")); labelList.add(new Label("大白菜","cabbage","vegetables")); for(Label label : labelList){ if(label.getParCode() == null){ LabelData labelData = new LabelData(label.getCode(), label.getName()); setChildren(labelData, labelList); result.add(labelData); } } System.out.println(123); } public static void setChildren(LabelData labelData, List<Label> labelList){ List<LabelData> labelDataList = new ArrayList<>(); for(Label label : labelList){ if(labelData.getCode().equals(label.getParCode())){ LabelData labelDataChildren = new LabelData(label.getCode(), label.getName()); if(!isLastChild(label.getCode(), labelList)){ setChildren(labelDataChildren, labelList); } labelDataList.add(labelDataChildren); } } labelData.setChildren(labelDataList); } public static boolean isLastChild(String code, List<Label> labelList){ boolean result = true; List<Label> filterResult = labelList.stream().filter(item -> code.equals(item.getParCode())).collect(Collectors.toList()); if(filterResult.size() > 0){ result = false; } return result; } }