[英]How do i filter a list of object and return that particular filtered object in Java 8
[英]How do I get nested filtered list with map and filter?
我是 Java 的新手,正在使用流學習 Java8。 我想過濾列表。 我需要嵌套列表的過濾列表是“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": [ ]
}
]
我有一些應該接近解決方案的東西,但沒有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
(以及現有列表),您需要forEach()
或基本循環而不是map()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.