Java 比较LinkedHashMap中的两个值以避免添加相同的值

Java 比较LinkedHashMap中的两个值以避免添加相同的值,java,android,linkedhashmap,Java,Android,Linkedhashmap,我有一个来自JSONarray的for循环,我将值添加到LinkedHashMap中。我希望避免添加相同的值。我不知道怎么做 for (int l = 0; l <stops_summaries2.length(); l++){ JSONObject stopObject2 = stops_summaries2.getJSONObject(l); String stopid2 = stopObject2.getString("id"); System.out.println("s

我有一个来自
JSONarray
的for循环,我将值添加到
LinkedHashMap
中。我希望避免添加相同的值。我不知道怎么做

for (int l  = 0; l <stops_summaries2.length(); l++){

JSONObject stopObject2 = stops_summaries2.getJSONObject(l);
String stopid2 = stopObject2.getString("id");   
System.out.println("stopid2 --->" + stopid2);
String stopurl2 = stopObject2.getString("url"); 
System.out.println("stopurl2 --->" + stopurl2);
String stopname2 = stopObject2.getString("name");
System.out.println("stopname2 --->" + stopname2);

LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();

    map.put(TAG_NAME, stopname2);
    map.put(TAG_SHORT, id);
    map.put(TAG_COLOR, stopid2);
    itemList.add(map);
}

for(int l=0;l您可以使用函数
containsKey(key)
containsValue(values)
检查地图是否包含某个键或值

编辑:我现在看到您正在每次迭代中创建一个新映射,这真的是您想要做的吗?该映射在for循环之外将不可用。我认为您需要在for循环之前声明映射,然后添加到它


编辑:更正了我回答中的一个错误,

在我看来,您应该避免在每次迭代中创建不同的映射,并将其用作数据的容器。您可以使用包装器类:

public class Item {

   String name;
   String id;
   String url;

   public Item(String nane, String id, String url) {
     this.name = name;
     this.id = id;
     this.url = url;
   }

   @Override
   public boolean equals(Object other){
     if (!(other instanceof Item)) return false;
      return id.equals( ((Item)other).id);
   }

}

和override equals检查两个对象是否相等。

但他有stops\u summares2.length()不同的映射我只想避免不同的值。但是HashMap中的所有键都是唯一的。如果你用现有的键放一些东西,旧的值会被新的值重写。你想避免吗?这是android中的列表视图。由于linkedhashmap,我在每行显示一个键/值对。数组中的一些值e相同,我只想在列表视图中显示其中一个。您的意思是,如果已经添加了等效映射,则不应执行
itemList.add(map)
?然后将itemList声明为一个集合。因此您不必担心,LinkedHashMap将只存储相同对的一个实例(因为任何映射中的键都是唯一的)