@Data
class User {
Integer id;
Integer parentId;
List<User> userList;
public User(Integer id, Integer parentId) {
this.id = id;
this.parentId = parentId;
}
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User(1, null));
userList.add(new User(2, 1));
userList.add(new User(3, 1));
}
}
请教一下怎样使用 lamdba 将 u2u3 set 到 u1 里
用 lamdba 总用不好
List<User> rootList = userResource.stream().filter(u-> u.getParentId() == null).collect(toList());
Set<User> userSet= new HashSet<>();
for(User u: rootList){
List<User> newList = new ArrayList<>();
for(User subUser: userResource){
if(subUser.getParentId == u.getId){
newList.add(subUser);
u.setUserList(newList);
}
}
userSet.add(u);
}
目前我用拆分成两个List rootList 代表根节点,userResource是所有数据
1
MinQ 2018-03-22 15:01:50 +08:00
等等不是 lambda 么?
|
2
yidinghe 2018-03-22 15:02:45 +08:00
这个用不到 lambda 表达式,但我猜你是想要这样:
```java import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class User { private int id; private int parentId; private List<User> userList = new ArrayList<>(); public User(int id, User... users) { this.id = id; this.userList.addAll(Arrays.asList(users)); this.userList.forEach(u -> u.parentId = id); } public static void main(String[] args) { User root = new User(1, new User(2, new User(3), new User(4)), new User(5, new User(6) ) ); } } ``` |
3
yidinghe 2018-03-22 15:04:37 +08:00
为什么回复不能用 markdown........
算了贴到别地方 https://gitee.com/yidinghe/codes/u3w7r5qz2ikxp9hotcd1n41 |
4
zhazi OP @yidinghe 结构是这样的,但是我数据是从数据库取的一个 List<User>里面有 parent 节点和 child 节点,我不想一层又一层遍历,我觉得 stream 应该能处理这样的需求
|
7
yidinghe 2018-03-22 15:47:42 +08:00
哦 这就是将集合元素构建成树结构,我这里给个现成的例子:
https://gitee.com/yidinghe/codes/q6lbevnaru5m08fixcw4740 |
8
leafin 2018-03-22 17:24:09 +08:00
试试这个
List<User> userList = userResource.stream() .peek(u -> u.setUserList(userResource.stream() .filter(su -> Objects.equals(u.getId(), su.getParentId())) .collect(toList()))) .filter(u -> u.getParentId() == null) .collect(toList()); |
9
zacard 2018-03-22 17:46:47 +08:00
private Set<User> something(List<User> userResource) {
Map<Integer, List<User>> groupMap = userResource.stream() .collect(Collectors.groupingBy(User::getParentId, Collectors.toList())); Map<Integer, User> rootMap = groupMap.remove(null).stream() .collect(Collectors.toMap(User::getId, Function.identity())); groupMap.forEach((k, v) -> rootMap.get(k).setUserList(v)); return new HashSet<>(rootMap.values()); } 没有测试过,不过大致是这个思路 |
10
waltyyy 2018-03-29 11:21:49 +08:00
```
Map<Integer, List<User>> parentIdUserMap = userResource.stream() .filter(u -> u.getParentId() != null) .collect(groupingBy(User::getParentId)); userResource.stream().filter(u -> u.getParentId() == null).map(u -> { u.setUserList(parentIdUserMap.get(u.getId())); return u; }).collect(toList()); ``` |