Search code examples
javaandroidandroid-listview

Android java: How correct send sorted data to listView?


I sorted data in format Map<Integer, FindedUser> where Integer is Timestamp in System.currentTimeMillis()/1000 and FindedUser class

Map<Integer, FindedUser> reverseSortedMap = new TreeMap<>(Collections.reverseOrder());
        reverseSortedMap.putAll(addedUsersMap);
    
for (Map.Entry<Integer, FindedUser> entry : reverseSortedMap.entrySet()) {
            FindedUser user = entry.getValue();
            System.out.println(entry.getKey()+" "+entry.getValue());
            helperMap.put(entry.getKey(), new FindedUser(user.getId(), user.getName(), user.getTimestamp()));
        }

and got correct data

1609093171 FindedUser{name='ccc', id='11', timestamp='1609093171'}
1609092871 FindedUser{name='bbb', id='10', timestamp='1609092871'}
1609092015 FindedUser{name='aaa', id='9', timestamp='1609092015'}

but when i send it to listView:

MyAdapterHash addedUsersAdapter = new MyAdapterHash(helperMap);
        addedUsersListView.setAdapter(addedUsersAdapter);
        addedUsersAdapter.notifyDataSetChanged();

result is not sorted correct:

1609092015 FindedUser{name='aaa', id='9', timestamp='1609092015'}
1609093171 FindedUser{name='ccc', id='11', timestamp='1609093171'}
1609092871 FindedUser{name='bbb', id='10', timestamp='1609092871'}

Where is the problem?


Solution

  • It looks like helperMap is of type HashMap which does not maintain the insertion order.

    Change the type of helperMap to LinkedHashMap which gives you a predictable iteration order.