[{
"bookName": "1",
"bookTypeId": "",
"attr": {
"typeId": "type-a"
}
},
{
"bookName": "2",
"bookTypeId": "",
"attr": {
"typeId": "type-b"
}
}
]
需要把 attr 对象中的 typeid 设置到外面 bookid 中,attr 对象可能为空,返回还是 List<Book>。类似于这种伪代码。请问这种怎么优雅实现。
List<Book> collect = json.getBookList()
.stream()
.map(m -> m.setBookTypeId(m.getAttr().getTypeId())).collect(
1
uselessVisitor 2020-12-23 13:19:18 +08:00 via Android
你这样写挺好的
|
2
canbingzt 2020-12-23 13:47:01 +08:00 1
json.getBookList()
.stream() .filter(m -> m.getAttr() != null) .forEach(m -> m.setBookTypeId(m.getAttr().getTypeId())) |
3
mmdsun OP @beichenhpy 不行。。我这样写要把 setBookTypeId 方法给改了返回 Book 才行,现在 set 方法返回的是 void,而且 getAttr().getId 会报空指针。😅
|
4
6IbA2bj5ip3tK49j 2020-12-23 15:39:34 +08:00 1
json.getBookList()
.stream() .filter(m -> m.getAttr() != null &&m.getAttr().getTypeId()!=null ) .peek(m -> m.setBookTypeId(m.getAttr().getTypeId())) |
5
Rwing 2020-12-23 16:00:07 +08:00
C#欢迎您
var result = json.BookList .Where(b=>b.attr != null) .Select(b=>{ bookTypeId=b.attr.typeId; return b; }) .ToList(); |
6
taogen 2020-12-23 16:09:21 +08:00 1
|
7
taogen 2020-12-23 16:15:19 +08:00
If we want to process this data in parallel, we are going to distribute it among all the cores of our processors and we do not want to have any kind of visibility or synchronization issues that could lead to bad performances or errors. Avoiding this kind of interference means that we shouldn't modify the source of the data while we're processing it.
|
9
yuhuan66666 2020-12-23 16:19:55 +08:00
这个赋值位置不能用 map map 要求返回一个新对象,但你的需求实际上是在原对象上添加元素 应该用 peek
|
10
yuhuan66666 2020-12-23 16:21:12 +08:00
看一下 《 java8 实战》对 stream 讲用法还不错
|
11
liuxey 2020-12-23 16:37:19 +08:00
松散结构直接 stream 操作想想就可怕,NPE 教做人
|
12
6IbA2bj5ip3tK49j 2020-12-23 16:37:46 +08:00
|
13
mmdsun OP json.getBookList()
.stream() .peek(book -> m.getArrt()) .map(Arrt::getTypeId) .ifPresent(book::setBookTypeId)) .collect() 感谢大家,已解决。网上找到了类似写法。 明天试试看。 ( setBookTypeId 需要返回 Book 的 this ) 回 5 楼 c# linq 确实给编程语言贡献了很多。 @liuxey @yuhuan66666 @luban @canbingzt @beichenhpy @taogen @xgfan |