sandee
sandee

Reputation: 349

Why remove element of Map?

I am filtering the all list which ahve same lat,long in one list and put into an same list and put that list into map My code is as:-

private Collection<List<Applicationdataset>> groupTheList(ArrayList<Applicationdataset> arrayList)
  {
    Map<Key, List<Applicationdataset>> map = new HashMap<Key, List<Applicationdataset>>();
    for(Applicationdataset appSet: arrayList)
       {
        Key key = new Key(appSet.getLatitude(), appSet.getLongitude());
        List<Applicationdataset> list = map.get(key);
        if(list == null){
            list = new ArrayList<Applicationdataset>();

        }
        list.add(appSet);
             map.put(key, list);
    }
    return map.values();
}


public class Key {
    String _lat;
    String _lon;

    Key(String lat, String lon) {
        _lat = lat;
        _lon = lon;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Key key = (Key) o;

        if (!_lat.equals(key._lat)) return false;
        if (!_lon.equals(key._lon)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = _lat.hashCode();
        result = 31 * result + _lon.hashCode();
        return result;
    }
}

But When I am debuging my code according to xml which come from web-service there is 2 list which have same lat long and they are saving in same list in amp at time of debuging but when I go next step of debug the element of map which have 2 item list decrease and showing size 1 I am unable to rectify this issue.

Upvotes: 0

Views: 85

Answers (2)

Bohemian
Bohemian

Reputation: 425013

Your code looks OK: You've overridden equals() and hashCode() consistently.

Check for whitespace in the lat/lng values as the cause of your problems, perhaps trim() in the constructor:

Key(String lat, String lon) {
    _lat = lat.trim();
    _lon = lon.trim();
}

Also, you can simplify your code to this:

@Override
public boolean equals(Object o) {
    return o instanceof Key
        && _lat.equals(((Key)o)._lat))
        && _lon.equals(((Key)o)._lon));
}

@Override
public int hashCode() {
    // String.hashCode() is sufficiently good for this addition to be acceptable
    return _lat.hashCode() + _lon.hashCode();
}

Upvotes: 1

Viktor Stolbin
Viktor Stolbin

Reputation: 2939

Thats a bit hard to understand what you are trying to accomplish. But I believe the issue is that you are using both latitude and longitude in Key hashCode()/equals() implementation thats why second Applicationdataset in your input list replaces the first one in your map object. You should implement the case when related list was already put into map and do not replace it.

Upvotes: 0

Related Questions