0

I am working on a Java project where I have to use a Java stream to collect IDs of all the objects inside a list of objects.

Now I only want to collect IDs of those objects whose type matches a certain value.

What I am using:

List<String> skuGroupIds = skuGroupPagedResponseMap.getData().stream().map(this::getGroupId).collect(Collectors.toList());

Now I want to use the condition and I did this but this is giving syntax error:

List<String> skuGroupIds = skuGroupPagedResponseMap.getData().stream().map(group->group.getCreatedType().equals(SkuGroupCreationType.SKU_GROUP_LOT)?this::getGroupId:return null;).collect(Collectors.toList());

getGroupID function used inside map

private String getGroupId(SkuGroupResponseDTO skuGroupResponseDTO){
    return skuGroupResponseDTO.getSkuId() + Constants.HYPHEN + skuGroupResponseDTO.getId();
}

How can I fix this so it doesn't cause a syntax error?

1
  • 2
    Why not just use filter() and then map()? Commented Apr 7, 2022 at 4:49

1 Answer 1

1

Your lambda inside map(), should look like this:

.map(group -> group.getCreatedType().equals(SkuGroupCreationType.SKU_GROUP_LOT) ? this::getGroupId : null)

Or like this:

.map(group -> {
    return group.getCreatedType().equals(SkuGroupCreationType.SKU_GROUP_LOT) ? this::getGroupId : null;
})

But it would be much better to use a filter(), as mentioned in comments:

List<String> skuGroupIds = skuGroupPagedResponseMap.getData()
     .stream()
     .filter(group -> group.getCreatedType().equals(SkuGroupCreationType.SKU_GROUP_LOT))
     .map(this::getGroupId)
     .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.