Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce the size of list with Java 8 stream

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;
}
like image 316
Tishy Tash Avatar asked Jan 17 '20 12:01

Tishy Tash


People also ask

How do I reduce the size of a list in Java?

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.

What is reduce () in Java8?

In Java 8, the Stream. reduce() combine elements of a stream and produces a single value. A simple sum operation using a for loop.

What is reduce in Java 8 streams?

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.

What is the purpose of the limit () method in Java 8?

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.


1 Answers

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.

like image 80
Naman Avatar answered Nov 14 '22 23:11

Naman