I have a list which contains another list Which has String values
[
["ax", "BX", "CX_123"],
["ax", "BX", "CD_124"],
["ax", "BX", "CY_456"]
],
[
["ax", "BX", "CB_456"],
["ax", "BX", "CX_564"],
["ax", "BX", "CZ_345"]
],[
["ax", "BX", "CE_234"],
["ax", "BX", "CM_235"],
["ax", "BX", "CX_4534"]
]
I have to filter the list which start with CX_ value in the inner list
The result should look like:
[
["ax", "BX", "CX_123"],
["ax", "BX", "CX_564"],
["ax", "BX", "CX_4534"]
]
CodePudding user response:
You can use stream and filter to retrieve the result with condition
@Test
public void test() {
List<String> row1 = Arrays.asList("AA","BB","CX_11");
List<String> row2 = Arrays.asList("CC","D","CD_11");
List<List<String>> list = Arrays.asList(row1,row2);
Assertions.assertEquals(row1, getFirstList(list,"CX_"));
Assertions.assertEquals(row2, getFirstList(list,"CD_"));
}
public List<List<String>> getAllList(List<List<String>> list,String key){
return list.stream().filter(this.contain(key)).collect(Collectors.toList());
}
public List<Map<String,String>> getListOfMap(List<List<String>> list,String key){
Function<List<String>,Map<String,String>> convertListToMap = (l)->{
Map<String,String> map = new LinkedHashMap<>();
map.put("name", l.get(1));
map.put("code", l.get(2));
return map;
};
return list.stream().filter(this.contain(key)).map(convertListToMap).collect(Collectors.toList());
}
public List<String> getFirstList(List<List<String>> list,String key){
return list.stream().filter(this.contain(key)).findFirst().get();
}
private Predicate<List<String>> contain(String key){
return (l)-> l.stream().anyMatch(s-> s.contains(key));
}
CodePudding user response:
You can do it by the following steps:
1. Declare a List<List<String>> will be returned
2. Foreach List<List<String>>, fetch each List<String>
2.1. With each List<String>, foreach it, fetch each string
2.2. If each string contains CX_ value, add this List<String> to the returned List<List<String>>