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

AlanBE :

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.

Deadpool :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132530&siteId=1