0

I have 5 variables with the following values.

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) {

        }
    });

after getting data from database, i have:

int john = 3;
int caleb = 15;
int justin = 30;
int loic = 20;
int lala = 0;

what I want is to classify them to have the first, the second, the third ..... according to their values, to have something like that.

justin = 30;
loic = 20;
caleb = 15;
john = 3;
lala = 0;

I'm using java, Android studio. thank you in advance.

deslok
  • 51
  • 7

1 Answers1

2

So, instead of having your 5 variables, initialize a map this way:

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);

And then, your method should be:

@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());
    }
}
Villat
  • 1,455
  • 1
  • 16
  • 33