我有一个以下格式的 JSON 响应,我将对其进行解析以获取每个键的键 (key_as_String) 和值(Expected_Usage 和 Actual_Usage)。
"aggregations": {
"Inner_aggregation": {
"doc_count": 366,
"Hours_aggregation": {
"doc_count": 366,
"by_day": {
"buckets": [
{
"key_as_string": "2016-01-11",
"key": 1452556800000,
"doc_count": 1,
"Expected_Usage": {
"value": 5
},
"Actual_Usage": {
"value": 3
}
},
{
"key_as_string": "2016-01-12",
"key": 1452556800000,
"doc_count": 1,
"Expected_Usage": {
"value": 43
},
"Actual_Usage": {
"value": 2
}
},
.........,
.........
]
}
}
}
}
}
我想保留插入顺序,因为 Elastic Search 返回的 KEYS 已经排序。我还想为每个键维护 VALUES 的顺序。
考虑为此使用 LinkedHashmap 和 LinkedHashSet。
LinkedHashMap<String, LinkedHashSet<Integer>> LinkedMap =
new LinkedHashMap<String,LinkedHashSet<Integer>>();
LinkedHashSet<Integer> LinkedSet =
new LinkedHashSet<Integer>();
LinkedSet.add(3);
LinkedSet.add(4);
LinkedSet.add(2);
LinkedMap.put("2016/03/11",LinkedSet);
for(Map.Entry m:LinkedMap.entrySet()){
System.out.println("Key is : " + m.getKey() + " Values: " + m.getValue());
}
在内存和性能方面是否有更好的选择?
最佳答案
有很多选择,主要取决于您将如何使用获取的数据 - 例如如果您不关心调用代码修改您的数据,设计具有公共(public)成员的结构将导致最小的 CPU 压力。
The maximum possible key values in the response is 365 and there'll be only 2 values for each Key.
我明白了。我建议删除 LinkedHashSet
并编写一个自定义类来保存这两个整数未装箱(不要浪费 CPU 将 int
转换为 Integer
和返回):
public class ExpectedVsActual {
// if you don't care too much of your data integrity
// along other lines of coding, make those public
// and forget about getters
protected int expected;
protected int actual;
public ExpectedVsActual(int exp, int act) {
this.expected=exp;
this.actual=act;
}
public int getExpected() {
return this.expected;
}
public int getActual() {
return this.actual;
}
}
然后
LinkedHashMap<String, ArrayList<ExpectedVsActual>> myMap=...; // etc
当然,如果您不需要通过键进行搜索,那么您就不需要 map 。
如果您希望每个键都有单独的条目,也许最好将每个条目包装为一个结构:
public class MyEntryRepresentation {
protected String dateStr;
// ArrayList: faster iteration by position
// LinkedList: memory conservative - doesn't allocate more than necessary
protected List<ExpectedVsActual> data;
public MyEntryRepresentation(String date)
this.dateStr=date;
this.data=new ArrayList<ExpectedVsActual>();
}
public void addEntry(int expected, int actual) {
this.data.add(new ExpectedVsActual(expected, actual));
}
public List<ExpectedVsActual> getValues() {
// if you don't care what the caller will do with your List
return this.data;
// If you want to forbid them to modify the returned list
// return Collections.unmodifiableList(this.data);
}
public String getDateStr() {
return this.date;
}
}
然后
LinkedHashMap<String, MyEntryRepresentation> map=... etc;
map.add(entry.getDateStr(), entry);
关于java - LinkedHashMap 中的 LinkedHashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39948969/