david
david

Reputation: 313

java 8 stream groupBy and new object creation

Let's say I have two classes C1 and C2 where C2 is used by the constructor of C1:

public class C1
{
    public C1( C2 o2 ){ ... }

    public String getProperty()
    {
        String result;
        ...
        return result;
    }
}

Now, I have a list of C2 objects (List list) that I would like to stream and filter using a condition on the getProperty() of C1 created from the C2 objects that are streamed.

Is there a way to do this with a stream?

List<C2> list = ...
List<C2> result = list.stream().filter( XXXX )

where I guess I should have XXXX that creates a C1 object using a C2 object from the stream and compares its getProperty() (e.g., "value".equals (o2.getProperty())

Is this possible at all?

Upvotes: 1

Views: 401

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

You'll be throwing away the instances, but sure

list.stream().filter(c2 -> "value".equals(new C1(c2).getProperty())).collect(toList());

This does seem kind of backwards. Perhaps the logic for this property should go in the C2 class or some utility class (static method) or instance that provides the property for a given C2 instance.

Upvotes: 5

Related Questions