如何移除POJO集合中所有id等于指定值的元素?
Hey there! Let's work through this problem together. First off, I notice the sample data from your server isn't valid JSON for a collection of Item objects—right now it's a single object with duplicate keys, which isn't what you need. A valid JSON array for your Item collection should look like this:
[ {"id":2,"name":"Ali"}, {"id":3,"name":"janice"}, {"id":2,"name":"Ali"}, {"id":5,"name":"tupac"}, {"id":2,"name":"Ali"}, {"id":8,"name":"William"}, {"id":2,"name":"Ali"} ]
First, make sure you parse this valid JSON into a List<Item> using a library like Jackson or Gson. For example, with Jackson:
ObjectMapper objectMapper = new ObjectMapper(); List<Item> originalItems = objectMapper.readValue(yourJsonString, new TypeReference<List<Item>>() {});
Now, let's cover a few straightforward ways to batch remove all items where id == 2:
1. Java 8+ Stream API (Clean & Concise)
This is my go-to for readability. We'll create a new filtered collection without modifying the original:
import java.util.stream.Collectors; List<Item> filteredItems = originalItems.stream() .filter(item -> item.getId() != 2) // Keep items where id is NOT 2 .collect(Collectors.toList());
2. Iterator (Modify Original Collection)
If you need to remove elements directly from the original list (instead of creating a new one), use an Iterator to avoid ConcurrentModificationException (which happens if you try to remove items with a regular for-loop):
import java.util.Iterator; Iterator<Item> iterator = originalItems.iterator(); while (iterator.hasNext()) { Item currentItem = iterator.next(); if (currentItem.getId() == 2) { iterator.remove(); // Safely remove the element } }
3. Using Guava (Optional, for Utility Lovers)
If you're using the Guava library, you can use Collections2.filter to create a filtered view, then convert it to a list if needed:
import com.google.common.collect.Collections2; // Creates a filtered view (changes to original list affect this view) Collection<Item> filteredView = Collections2.filter(originalItems, item -> item.getId() != 2); // If you want an independent list: List<Item> filteredList = new ArrayList<>(filteredView);
All these methods will leave you with only the items where id is 3, 5, or 8—exactly what you need!
内容的提问来源于stack exchange,提问作者ken

