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?
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());