我有5个具有以下值的变量。
int john = 0;
int caleb = 0;
int justin = 0;
int loic = 0;
int lala = 0;
DatabaseReference productRef = FirebaseDatabase.getInstance().getReference().child("Product");
productRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
String getName = ds.child("name").getValue(String.class);
if (getName.equals("john")){
john++;
}else if (getName.equals("caleb")){
caleb++;
}else if (getName.equals("justin")){
justin++;
}else if (getName.equals("loic")){
loic++;
}else if (getName.equals("lala")){
lala++;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
从数据库获取数据后,我有:
int john = 3;
int caleb = 15;
int justin = 30;
int loic = 20;
int lala = 0;
我想要的是根据它们的值将它们分类为具有第一个,第二个,第三个.....,以具有类似的东西。
justin = 30;
loic = 20;
caleb = 15;
john = 3;
lala = 0;
我正在使用Java,Android Studio。 预先谢谢你。
答案 0 :(得分:1)
因此,不用拥有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());
}
}