使用import com.google.common.collect.Maps;如何优化这段代码
private void setBearCapacityData(List<List> bearCapacityList, Map<String, Object> data) { //System.out.println("bearCapacityList = " + bearCapacityList);
List<Double> cupPercentageList = new ArrayList<>();
List<Double> storagePercentageList = new ArrayList<>();
List<Double> diskPercentageList = new ArrayList<>();
Map<String,Object> useableMaps = Maps.newHashMap();
Map<String,Object> useableMaps1 = Maps.newHashMap();
Map<String,Object> useableMaps2 = Maps.newHashMap();
List<Map<String,Object>> useableDataList = Lists.newArrayList();
for (Object object0: bearCapacityList.get(0)) {
CpuUseable cpuUseable = (CpuUseable)object0;
cupPercentageList.add(cpuUseable.getPercentage());
}
useableMaps.put("name","cpu可用率");
useableMaps.put("percentage", cupPercentageList);
useableDataList.add(useableMaps);
for (Object object1: bearCapacityList.get(1)) {
StorageUseable storageUseable = (StorageUseable)object1;
storagePercentageList.add(storageUseable.getPercentage());
}
useableMaps1.put("name","内存可用率");
useableMaps1.put("percentage", storagePercentageList);
useableDataList.add(useableMaps1);
for (Object object2: bearCapacityList.get(2)) {
DiskUseable diskUseable = (DiskUseable)object2;
diskPercentageList.add(diskUseable.getPercentage());
}
useableMaps2.put("name","磁盘可用率");
useableMaps2.put("percentage", diskPercentageList);
useableDataList.add(useableMaps2);
data.put("bearCapacityData", useableDataList);
}
回答:
String[] names = new String[] {"cpu可用率", "内存可用率", "磁盘可用率"};List<Map<String,Object>> useableDataList = Lists.newArrayList();
for (int i = 0; i < names.length; i++) {
Map<String, Object> map = Maps.newHashMap();
List<Double> list = new ArrayList<>();
for (Object obj : bearCapacityList.get(i)) {
Method method = obj.getClass().getMethod("getPercentage");
// 加个强转呗
list.add((Double) method.invoke(obj));
}
// 下边这两句我记得好像是可以用
// Maps.of("name", names[i], "percentage", list);
// 来写,但是我忘了谷歌这个包还有没有这个接口了。
map.put("name", names[i]);
map.put("percentage", list);
// 这里写错了,应该是 useableDataList
useableDataList .add(map);
}
以上是 使用import com.google.common.collect.Maps;如何优化这段代码 的全部内容, 来源链接: utcz.com/a/166398.html