whatislife
whatislife

Reputation: 61

Java collector class usage

So I am trying to make sense of this but translating into simple statement. But I am having trouble doing so.

Var is a List class that holds bunch of values. I have a vague understanding of the code. This code is grabbing values that has not been assigned from assigned and inputting it into List of unassigned. But I don't understand how to translate it into simple statement to help me understand it more clearly.

List<Var> unassigned = assigned.stream()
                .filter((Var grabNear).(!grabNear.isAssigned()))
                .collect(Collectors.toList());

This is what I have so far. Is this correct?

List<Var> unassigned = assigned;
Var grabNear;
            for(int i = 0; i < assigned.size(); ++i)
            {
                grabNear = assigned.get(i);
                if(!grabNear.isAssigned())
                {
                    unassigned.add(grabNear);
                }
            }

Upvotes: 4

Views: 96

Answers (1)

Eran
Eran

Reputation: 393936

Collectors.toList() creates a new List, so your code should look like this in order to be equivalent to the Java 8 code :

List<Var> unassigned = new ArrayList<>();
Var grabNear;
for(int i = 0; i < assigned.size(); ++i)
{
    grabNear = assigned.get(i);
    if(!grabNear.isAssigned())
    {
        unassigned.add(grabNear);
    }
}

P.S. the Java 8 code has an error in the filter method call. It should be :

.filter((Var grabNear) -> !grabNear.isAssigned())

or

.filter(grabNear -> !grabNear.isAssigned())

Upvotes: 2

Related Questions