Amit
Amit

Reputation: 196

Remove value from List of Map in java

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.

Upvotes: 0

Views: 6564

Answers (3)

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

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

Upvotes: 1

Tudor Vintilescu
Tudor Vintilescu

Reputation: 1460

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533472

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

Upvotes: 3

Related Questions