在现有的 HashMap 中添加元素
以下代码在 json 解析器的帮助下获取元素。我的问题是,当我找到相同的值时,我想在现有哈希映射中放置一个新元素(例如“title2”)相同的价值! 我的第一个想法是在第一个循环之后创建一个新循环(for...)并在此处执行一些操作,但这很难。我找不到有效的方法。 有解决办法吗?有什么想法吗?
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
//Get the elements
HashMap<Integer, String> mapCompare = new HashMap<Integer, String>();
JSONArray data = json.getJSONArray("data");
//Loop the array
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> mapInfo = new HashMap<String, String>();
JSONObject e = data.getJSONObject(i);
mapInfo.put("id", e.getString("id"));
mapInfo.put("title", e.getString("title"));
mapInfo.put("value", e.getString("value"));
if (mapCompare.containsValue(e.getString("value")) {
mapInfo.put("isSame?", "yes");
} else {
mapInfo.put("isSame?", "no");
}
mapCompare.put(i, e.getString("value"));
listInfo.add(mapInfo);
}
// a new for ??? and how ???
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return listInfo;
}
The folowing code takes elements with assistance of a json parser. My problem is, when i find a same value then i want to put an new element (eg "title2") in the existing hashmap with the same value!
My first thought is to make an new loop (for...) after the first loop and to do some actions here but it's hard. I can not find an efficient way.
Is there a solution for this? Any idea?
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
//Get the elements
HashMap<Integer, String> mapCompare = new HashMap<Integer, String>();
JSONArray data = json.getJSONArray("data");
//Loop the array
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> mapInfo = new HashMap<String, String>();
JSONObject e = data.getJSONObject(i);
mapInfo.put("id", e.getString("id"));
mapInfo.put("title", e.getString("title"));
mapInfo.put("value", e.getString("value"));
if (mapCompare.containsValue(e.getString("value")) {
mapInfo.put("isSame?", "yes");
} else {
mapInfo.put("isSame?", "no");
}
mapCompare.put(i, e.getString("value"));
listInfo.add(mapInfo);
}
// a new for ??? and how ???
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return listInfo;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HashMap
旨在高效地进行键查找,而不是值查找。听起来您可能需要双向地图 - 看看 Guava 的
BiMap
< /a>界面,可能还有HashBiMap
实现。或者,您可以使用
Multimap
其中每个键可以映射到多个值 - 因此您将拥有一个value
条目,其中包含您的所有值已添加该密钥。目前尚不完全清楚您想要做什么,但我希望其中一种方法适合您。
HashMap
is designed to be efficient for key lookups, not value lookups.It sounds like you might want a bidirectional map - have a look at Guava's
BiMap
interface and probably theHashBiMap
implementation.Alternatively, you could use a
Multimap
where each key can map to multiple values - so you'd have a single entry forvalue
which would contain all of the values you've added for that key.It's not entirely clear what you're trying to do, but I'd expect one of those approaches to work for you.