0

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

4
  • Please post your code and explain your issues with it Commented May 2, 2021 at 12:57
  • 1
    m trying to use JavaStream ... - It's a very basic problem. Post your code so that we can understand where exactly you are stuck. Commented May 2, 2021 at 13:03
  • I've added my one line solution from Swift but can't understand Java Stream syntax for the same. Commented May 2, 2021 at 13:08
  • List B should be a Set. Commented Nov 21, 2022 at 18:56

2 Answers 2

1
  • 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/

Sign up to request clarification or add additional context in comments.

Comments

0

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


}

1 Comment

Thank you very much. it worked. this bit i was missing -> !filterNot.contains(item.id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.