1 回答
TA贡献1884条经验 获得超4个赞
因此,不要使用 5 个变量,而是以map这种方式初始化:
Map<String, Integer> map = new HashMap<>();
map.put("john", 0);
map.put("caleb", 0);
map.put("justin", 0);
map.put("loic", 0);
map.put("lala", 0);
然后,你的方法应该是:
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Integer currentCount = 0;
for (DataSnapshot ds: dataSnapshot.getChildren()){
String getName = ds.child("name").getValue(String.class);
currentCount = map.get(getName);
map.put(getName, currentCount+1);
}
//You can print your values using this
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
entryList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
for (Map.Entry<String, Integer> entry : entryList) {
System.out.printf("%s = %s; \n", entry.getKey(), entry.getValue());
}
}
添加回答
举报