利用java Stream 创建分类树

创建分类对象

public class CityClassify {
protected Integer id;
protected String name;
protected Integer pid;
protected Integer level;
protected List children;
public CityClassify(Integer id, String name, Integer pid,Integer level) {
super();
this.id = id;
this.name = name;
this.pid = pid;
this.level=level;
}
}

获取城市集合

public static List getList(){
CityClassify CountryClassify1=new CityClassify(1,“山西”,0,1);
CityClassify CountryClassify2=new CityClassify(2,“太原”,1,2);
CityClassify CountryClassify3=new CityClassify(3,“吕梁”,1,2);
CityClassify CountryClassify4=new CityClassify(4,“大同”,1,2);
CityClassify CountryClassify5=new CityClassify(5,“河北”,0,1);
CityClassify CountryClassify6=new CityClassify(6,“石家庄”,5,2);
CityClassify CountryClassify7=new CityClassify(7,“保定”,5,2);
CityClassify CountryClassify8=new CityClassify(8,“陕西”,0,1);
CityClassify CountryClassify9=new CityClassify(9,“西安”,8,2);
CityClassify CountryClassify10=new CityClassify(10,“宝鸡”,8,2);
List asList = Arrays.asList(CountryClassify1,CountryClassify2,CountryClassify3,CountryClassify4
,CountryClassify5,CountryClassify6,CountryClassify7,CountryClassify8,CountryClassify9,CountryClassify10);
return asList;
}

进行分类操作

public static void main(String[] args) {
List list = getList();
Map<Integer, List> collect = list.stream().collect(Collectors.groupingBy(x -> x.getPid()));
list.stream().filter(x -> x.getLevel() < 2).forEach(x -> x.setChildren(collect.get(x.getId())));
System.out.println(collect.get(0));
}

分类结果

[CountryClassify [id=1, name=山西, pid=0, level=1,
children=[CountryClassify [id=2, name=太原, pid=1, level=2, children=null],
CountryClassify [id=3, name=吕梁, pid=1, level=2, children=null],
CountryClassify [id=4, name=大同, pid=1, level=2, children=null]]],
CountryClassify [id=5, name=河北, pid=0, level=1,
children=[CountryClassify [id=6, name=石家庄, pid=5, level=2, children=null],
CountryClassify [id=7, name=保定, pid=5, level=2, children=null]]],
CountryClassify [id=8, name=陕西, pid=0, level=1,
children=[CountryClassify [id=9, name=西安, pid=8, level=2, children=null],
CountryClassify [id=10, name=宝鸡, pid=8, level=2, children=null]]]]

猜你喜欢

转载自blog.csdn.net/weixin_41656377/article/details/105195585