I am working on a java project where I have to use 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();
}
Can anyone help me with this? any suggestions will be appreciated.
CodePudding user response:
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());