I want to reduce the size (delete some elements) of an ordered list of map objects. All objects of list should be discarded unless a certain condition is met. And when that condition is met all next elements of that list should remained in the list. I have following piece of code. I want to do the same with Java 8.
public List<Map<String, String>> doAction(List<Map<String, String>> dataVoMap) {
List<Map<String,String>> tempMap = new ArrayList<>();
boolean found = false;
for(Map<String, String> map: dataVoMap){
if(map.get("service_id").equalsIgnoreCase("passed value") || found){
found = true;
tempMap.add(map);
}
}
dataVoMap = tempMap;
return dataVoMap;
}
trimToSize() method trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.
In Java 8, the Stream. reduce() combine elements of a stream and produces a single value. A simple sum operation using a for loop.
A reduction is a terminal operation that aggregates a stream into a type or a primitive. The Java 8 Stream API contains a set of predefined reduction operations, such as average , sum , min , max , and count , which return one value by combining the elements of a stream.
The limit method of the Stream class introduced in Java 8 allows the developer to limit the number of elements that will be extracted from a stream. The limit method is useful in those applications where the user wishes to process only the initial elements that occur in the stream.
You are looking for a dropWhile
operation, but an in-built implementation of that would require Java-9 and above:
public List<Map<String, String>> doAction(List<Map<String, String>> dataVoMap) {
return dataVoMap.stream()
.dropWhile(m -> !"passed value".equalsIgnoreCase(m.get("service_id")))
.collect(Collectors.toList());
}
Note: I have made an edit to the existing code to avoid NPE when there could be a Map
in the List
without the key service_id
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With