Yankee Yankee - 2 days ago 5
Android Question

Filter a list of objects in Android using gradle-retrolambda and Lightweight-Stream-API

I am trying to filter a List of Objects in Java in my Android App, for this I followed this answer (Java 8 suggestion) , but as Lambdas aren't supported in Android SDK, I used gradle-retrolambda but I get this runtime-error

java.lang.NoSuchMethodError: No interface method stream()Ljava/util/stream/Stream; in class Ljava/util/List; or its super classes (declaration of 'java.util.List' appears in /system/framework/core-libart.jar)


This is the line of code I am using:

List<CaseDetails> closedCaseDetailsList = caseDetailsList.stream().filter(item -> item.caseClosed.equals(true)).collect(Collectors.toList());


I believe it should work as gradle-retrolambda should be taking care of the Lambdas on Java7.

Next, I tried Lightweight-Stream-API along with gradle-retrolambda and changed my code a little, according to the usage of Lightweight-Stream-API

List<CaseDetails> closedCaseDetailsList = Stream.of(caseDetailsList).filter(item -> item.caseClosed.equals(true)).collect(Collectors.toList());


But it gives me an error over
Collectors.toList()
saying

collect
(com.annimon.stream.Collector<? super com.example.yankee.cw.CaseDetails,java.lang.Object,java.lang.Object>)
in Stream cannot be applied
to
 (java.util.stream.Collector<T,capture<?>,java.util.List<T>>)


I also tried explicitly type-casting the
Stream
to
List<CaseDetails>
but that didn't work (of course).

I tried Slack communities, SO Chat-rooms but couldn't find a solution. The closest thing I found to my problem was this question but it is a different error.

Thanks

Answer

I can only give you an example for streamsupport

import java.util.Arrays;
import java.util.List;

import java8.util.stream.Collectors;
import java8.util.stream.StreamSupport;
import static java.lang.Boolean.TRUE;
import static java.lang.Boolean.FALSE;

public class CaseDetails {

    Boolean caseClosed = FALSE;

    public CaseDetails(Boolean caseClosed) {
        this.caseClosed = caseClosed;
    }

    public String toString() {
        return "caseClosed: " + caseClosed;
    }

    public static void main(String[] args) {
        List<CaseDetails> caseDetailsList = Arrays.asList(
                new CaseDetails(TRUE), new CaseDetails(FALSE), new CaseDetails(
                        TRUE));
        List<CaseDetails> closedCaseDetailsList = StreamSupport
                .stream(caseDetailsList)
                .filter(item -> item.caseClosed.equals(TRUE))
                .collect(Collectors.toList());

        System.out.println(closedCaseDetailsList);
    }
}

Hope this helps.

Comments