如何按降序对映射项的键值进行排序?

时间:2019-05-27 12:55:16

标签: java android firebase firebase-realtime-database

我对Java还是比较陌生的,使用比较器进行的整个排序对我来说有点混乱。

是否可以在不使用比较器的情况下按降序对下面代码的当前输出进行排序?

或者我有一种更简单的方法来理解如何对所述值进行排序。

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot , String s) {
        Map<String, Object> userInfo = (Map<String, Object>)dataSnapshot.getValue();
        String username = (String) userInfo.get("username");

        Map<String, Long> steps = (Map<String, Long>) userInfo.get("steps");

        long existingSteps = 0;
        for (Map.Entry<String, Long> step : steps.entrySet()) {
            existingSteps += Long.valueOf(step.getValue());
        }

        arrayList.add(new String( username + "  -  " + "steps:  " + existingSteps));

        arrayAdapter = new ArrayAdapter<>(Leaderboard.this , 
        android.R.layout.simple_list_item_1 , arrayList);

        listView.setAdapter(arrayAdapter);
}

此代码的当前输出为:

John Doe I - Steps: 79
John Doe II - Steps: 111
John Doe III - Steps: 0
John Doe IV - Steps: 88
John Doe V - Steps: 12
John Doe VI - Steps: 0

是否可以获取此代码以运行以下输出:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

Database Structure

1 个答案:

答案 0 :(得分:2)

我能想到的最简单的解决方案是在每个用户对象下添加步骤总数作为新属性。在这种情况下,您还需要做另一件事,那就是使用每天获得的步骤数来增加该属性。您的新架构应如下所示:

Firebase-root
  |
  --- user
       |
       --- userId
            |
            --- steps
            |    |
            |    --- //daily steps
            |
            --- target: 100
            |
            --- username: "John Doe I"
            |
            --- totalNumberOfSteps: 111

要根据totalNumberOfSteps属性以升序排列用户,请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
Query query = userRef.orderByChild("totalNumberOfSteps");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String username = ds.child("username").getValue(String.class);
            long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
            Log.d(TAG, username + " - Steps: " + totalNumberOfSteps);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

然后按降序排列,请从以下帖子中查看我的答案:

最后,logcat中的结果将是:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0