我是Java的新手,可以通过流学习Java8。 我想过滤列表。 我需要带有nestedlist的筛选列表是“ 22”。 但是我努力做到这一点。有人救了我吗?
我在下面放了一些简单的代码。 我像下面这样尝试过,但是现在可以了。
List<Custom> list = new ArrayList<>();
list.stream().map(
x -> x.getNestedList.stream().filter(
y->y.getValue.equals("22")
)
)
Before
[
{
"a":"1",
"nestedlist": [ {"11"},
{"22"},
{"33"} ]
},
{
"a":"2",
"nestedlist": [ {"22"},
{"44"} ]
},
{
"a":"3",
"nestedlist": [ {"11"},
{"33"} ]
},
{
"a":"4",
"nestedlist": [ {"b":"11"} ]
}
]
After
(Nestedlist has filtered by "22", but parent list still has whole element)
[
{
"a":"1",
"nestedlist": [ {"22"}]
},
{
"a":"2",
"nestedlist": [ {"22"} ]
},
{
"a":"3",
"nestedlist": [ ]
},
{
"a":"4",
"nestedlist": [ ]
}
]
答案 0 :(得分:0)
我有一些应该接近解决方案的东西,但是没有nestedList的定义,这只是草稿。您将不得不使其适应您的代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Scratch {
static class Custom<T>{
String a;
List<T> nestedList;
public Custom(String a, List<T> nestedList) {
this.a = a;
this.nestedList = nestedList;
}
public Custom(String a, T... nestedList) {
this.a = a;
this.nestedList = Arrays.asList(nestedList);
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public List<T> getNestedList() {
return nestedList;
}
public void setNestedList(List<T> nestedList) {
this.nestedList = nestedList;
}
@Override
public String toString() {
return "Custom{" +
"a='" + a + '\'' +
", nestedList=" + nestedList +
'}' +
'\n';
}
}
public static void main(String... args){
List<Custom> list = new ArrayList<>();
list.add(new Custom<String>("1", "11", "22", "33"));
list.add(new Custom<String>("2", "22", "44"));
list.add(new Custom<String>("3", "11", "33"));
List result = list.stream().map(
x -> new Custom(x.getA(), x.getNestedList().stream().filter(y -> y.equals("22")).collect(Collectors.toList()))
).collect(Collectors.toList());
System.out.println("input: "+list);
System.out.println("result: "+result);
}
}
哪个作为输出
input: [Custom{a='1', nestedList=[11, 22, 33]}
, Custom{a='2', nestedList=[22, 44]}
, Custom{a='3', nestedList=[11, 33]}
]
result: [Custom{a='1', nestedList=[[22]]}
, Custom{a='2', nestedList=[[22]]}
, Custom{a='3', nestedList=[[]]}
]
您的代码的主要问题(如果我理解您要正确执行的操作,我绝对不确定),您正在将初始Custom
对象映射到Stream
对象nestedList的内容。您需要做的是将一个Custom
映射到一个新的更新的Custom
(我做了什么)或更新您需要{的现有Custom
(以及现有列表) {1}}或基本循环而不是forEach()