-1

I have a for loop from a JSONarray and I add the values to a LinkedHashMap. I would like to avoid adding identical values. I don't know how to do this.

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);
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Xavier
  • 270
  • 1
  • 7
  • 17
  • But all the keys in HashMap are unique. if you put something with the existing key, the old value will be just over-written with the new one. Do you want to avoid that? – nikis Feb 19 '14 at 10:07
  • It's for a list view in android. I display on each row a key/value pair thanks to the linkedhashmap. Some values in the array are identical and I only want to display one of them in the list view. – Xavier Feb 19 '14 at 10:11
  • do you mean that `itemList.add(map)` should not be done if an equivalent map is already added? Then declare itemList as a Set. – Alexei Kaigorodov Feb 19 '14 at 10:15
  • So you don't have to worry about that, LinkedHashMap will store only one instance of identical pairs (since keys in any Map are always unique) – nikis Feb 19 '14 at 10:15

2 Answers2

0

You can use the functions containsKey(key) and containsValue(values) to check if the map contains a certain key or value.

Edit: I see now that you are creating a new Map on each iteration, is that really what you want to do? That map will not be available outside of the for loop. I think you need to declare the Map before the for loop and then add to it.

Edit: corrected a mistake in my answer,

Petter
  • 4,053
  • 27
  • 33
0

In my opinion you should avoid to create a different map at each iteration and use it like a container for your data. You could have a wrapper class:

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

}

and override equals to check if two objects are equals.

Blackbelt
  • 156,034
  • 29
  • 297
  • 305