Remove value from List of Map in java

2019-06-12 07:05发布

问题:

Remove value from list in java containing map

I am having list in this form:

List: [{id=1,c_id=3,value=5},{id=1,c_id=2,value=5},{id=1,c_id=3,value=5},{id=2,c_id=1,value=5},       
        {id=2,c_id=null,value=5}}];

In result I am trying to get

List: [{id=1,c_id=3,value=5},,{id=1,c_id=2,value=5},{id=2,c_id=1,value=5}}]

For same id if c_id is same it should be removed and also if c_id is null it should be removed.

回答1:

You can do

for(Iterator<Map<String, Object>> iter = list.iterator(); iter.hasNext(); ) {
    Map<String, Object> map = iter.next();
    Object c_id = map.get("c_id");
    if (c_id == null || c_id.equals(matching_c_id))
        iter.remove();
}


回答2:

I think a solution could be the following one and I think it is readable.

First, construct a set element proxy for your object type:

public class MyTypeProxy {

     private MyType obj;

     public MyTypeProxy(MyType obj) {

         this.obj = obj;

     }

     public MyType getObj() { return this.obj; }

     public int hashcode() {

         return obj.getC_id() ^ obj.getId();

     }

     public boolean equals(Object ref) {

         if (ref.getClass() != MyTypeProxy.class) {
             return false;
         }
         return 
              ((MyTypeProxy)ref).obj.getC_id() == this.obj.getC_id() &&
              ((MyTypeProxy)ref).obj.getId() == this.obj.getC_id();
     }
}

Then, in your code, you can construct a HashSet.

HashSet<MyTypeProxy> set = new HashSet<MyTypeProxy>();

for (MyType mt : list) {
    if (mt.getC_id() != null){
        set.add(new MyTypeProxy(myList));
    }
}

The following does two things. First, it excludes objects with a null c_id field and second, it filters out objects with the same id and c_id combination. You might want to consider if keeping the first one is ok or not (that is what the above code does).

The set now contains exactly what you need.



回答3:

Guava solution:

Iterables.removeIf(list, new Predicate<Element>(){
    @Override public boolean apply(Element e) {
        return e.c_id == null || e.c_id.equals(matching_c_id);
}});


标签: java list map