Joe
Joe

Reputation: 301

Use Java Stream to filter list based on values from second list

I'm trying to Filter a list of objects based on values from second list.

List A:

[
   {
      "id":"12345",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   },
   {
      "id":"34567",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   },
   {
      "id":"56789",
      "name":"nameOfItem",
      "description":"descriptionOfItem"
   }
]

List B:

["12345", "56789"]

Now i want to remove the item of List A with IDs available in List B.

Im trying to use JavaStream but can't understand the syntax and i'm trying ForEach loop but its not working properly.

I've done something similar in Swift as following.

            if let allModOptions = allModifersList?.first?.options {
                let excludedIDs = pObj?.excluded_ids
                if excludedIDs!.count > 0 {
                   let allowedOptions = allModOptions
                   ->>>>    **.filter{ !excludedIDs!.contains($0.id!)}** <<<<-
                        .filter{c in c.deleted_at == nil}.sorted {
                        $0.index ?? 0 < $1.index ?? 0
                       }
                
                    allModsList?.first?.options = allowedOptions
                
                }
               modisList.append(contentsOf: allModsList!)
            }

Any help is appreciated

Upvotes: 0

Views: 7214

Answers (2)

Leon the Logician
Leon the Logician

Reputation: 308

  • If I understand correctly, you are given the following information:
    • a class with 3 fields: id, name, description. Lets call this class Item.
    • a list of ids of Items which should be removed from List A. Lets call this list, idsOfItemsToRemove.
    • a list of all Items to evaluate
    • an expected list; a list of Items which do not contain any value present in idsOfItemsToRemove.
  • If the above assumptions are true, then the code snippet below should be indicative of what you are seeking to do.
@Test
public void test() {
    // given
    Integer idOfItemToBeRemoved1 = 12345;
    Integer idOfItemToBeRemoved2 = 56789;
    Item itemExpectedToBeDeleted1 = new Item(idOfItemToBeRemoved1, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeDeleted2 = new Item(idOfItemToBeRemoved2, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeRetained1 = new Item(34567, "nameOfItem", "descriptionOfItem");
    Item itemExpectedToBeRetained2 = new Item(98756, "nameOfItem", "descriptionOfItem");


    List<Integer> idsOfItemsToRemove = Arrays.asList(
            idOfItemToBeRemoved1,
            idOfItemToBeRemoved2);

    List<Item> listOfItems = Arrays.asList(
            itemExpectedToBeDeleted1,
            itemExpectedToBeDeleted2,
            itemExpectedToBeRetained1,
            itemExpectedToBeRetained2);

    List<Item> expectedList = Arrays.asList(
            itemExpectedToBeRetained1,
            itemExpectedToBeRetained2);

    // when
    List<Item> actualList = listOfItems
            .stream()
            .filter(item -> !idsOfItemsToRemove.contains(item.getId()))
            .collect(Collectors.toList());

    // then
    Assert.assertEquals(expectedList, actualList);
}

This code has also been pushed to Github.

https://raw.githubusercontent.com/Git-Leon/stackoverflow-answers/master/javastreamfilter/

Upvotes: 1

yevhensh
yevhensh

Reputation: 410

you should use filter on main collection and !contains on List collection

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Scratch {
    static class Element {
        int id;
        String name;
        String description;

        public Element(int id, String name, String description) {
            this.id = id;
            this.name = name;
            this.description = description;
        }

        @Override
        public String toString() {
            return "Element{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", description='" + description + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        List<Element> elements = new ArrayList<>(Arrays.asList(
           new Element(12345, "nameofitem", "asdfafd"),
           new Element(34567, "nameofitem", "asdfafd"),
           new Element(56789, "nameofitem", "asdfafd")
        ));
        List<Integer> filterNot = new ArrayList<>(Arrays.asList(12345, 56789));
        List<Element> result = elements.stream().filter(item -> !filterNot.contains(item.id)).collect(Collectors.toList());

        result.forEach(System.out::println);
    }


}

Upvotes: 0

Related Questions