I want write a method where when you post a parameter fooName
it returns a list with all values that start with the given parameter. I wrote such a function but unfortunately it returns a list with only one, first found value that starts with fooName
. How to return a list with all matching values?
My getAllStreams
method looks like:
@GetMapping
@ResponseBody
public List<Stream> getAllStreams(@RequestParam("fooName") String fooName){
var optionalStream = streamService.getAllStreams().stream()
.filter(str -> str.getFooName().startsWith(fooName)).findAny();
if (optionalStream.isPresent()) {
List<Stream> targetLongList = optionalStream.stream()
.filter(str -> str.getFooName().startsWith(fooName))
.collect(Collectors.toCollection(ArrayList::new));
return targetLongList;
}
return null;
}
When I post the following example:
[
{
"value": "c30",
"fooName": "example2"
},
{
"value": "90",
"fooName": "example1"
}
]
I only get:
[
{
"value": "c30",
"fooName": "example2"
}
]
Why are doing it to two times. Also findAny will only give you one item
You could just do it with one line
return streamService.getAllStreams().stream()
.filter(str -> str.getFooName().startsWith(fooName)).collect(Collectors.toList())