@Data
public class Org {
private Integer id;
private Integer pid;
Org(Integer id, Integer pid) {
this.id = id;
this.pid = pid;
}
}
public static void main(String[] args) {
Org root = new Org(1,null);
Org org1 = new Org(2,1);
Org org2 = new Org(3,1);
Org org3 = new Org(4,2);
Org org4 = new Org(5,2);
List<Org> list = Arrays.asList(root,org1,org2,org3,org4);
Map<Integer, List<Org>> error = list.stream().collect(Collectors.groupingBy(Org::getPid));
Map<Integer, List<Org>> correct = list.stream().collect(Collectors.groupingBy(org -> Optional.ofNullable(org.getPid()).orElse(0)));
}