AlanBE
AlanBE

Reputation: 133

Java 8 how to remove item from arraylist with ids from array

How to remove item from arraylist with ids from array. I have tried:

List <Group> loadedGroupList = iGroupRepository.findAll();
String [] groupIds = StringUtils.split(selectionGroupsIds, ',');

for (int i = 0 ; i < groupIds.length; i++) {
    String groupId = groupIds[i];
    loadedGroupList.removeIf(x -> x.getId() != Long.parseLong(groupId));
}

But I get an empty arraylist. Please help. Thanks.

Upvotes: 2

Views: 788

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

groupIds is an String array, convert it into List<String> and use contains()

removes Group from loadedGroupList if groupId is in groupIds array

loadedGroupList.removeIf(x -> Arrays.asList(groupIds).contains(x.getId()));

removes Group from loadedGroupList if groupId is not in groupIds array

loadedGroupList.removeIf(x -> !Arrays.asList(groupIds).contains(x.getId()));

By using java-8 streams, filter Group that doesn't have id in String array groupIds

List<Group> result = loadedGroupList.stream()
                                    .filter(x->!Arrays.asList(groupIds).contains(x.getId()))
                                    .collect(Collectors.toList());

Upvotes: 3

Related Questions