Reduce the size of list with Java 8 stream

Tishy Tash :

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;
}
Naman :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414646&siteId=1