1

I create Map of users and put it in ArrayList

ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(NUMBER_OF_SHOWING_USERS);
for(int i=0;i< NUMBER_OF_SHOWING_USERS; i++) {
        m = new HashMap<String, Object>();
        m.put(ATTRIBUTE_NAME_TEXT_NAME, FriendNames.get(i));
        m.put(ATTRIBUTE_NAME_TEXT_RAITING, PointsList.get(i));
        m.put(ATTRIBUTE_NAME_IMAGE, PhotoAsBytesList.get(i));
        data.add(m);}

How can I sort each Map(Users) only for their Points?

Zhambul
  • 942
  • 9
  • 23
  • 1
    I'm flagging this as a duplicate of: http://stackoverflow.com/questions/5369573/how-sort-an-arraylist-of-hashmaps-holding-several-key-value-pairs-each – Gero Apr 20 '15 at 20:53
  • 1
    possible duplicate of [java arraylist HashMap how to sort?](http://stackoverflow.com/questions/14682079/java-arraylist-hashmap-how-to-sort) – Abdallah Alaraby Apr 20 '15 at 20:54

1 Answers1

0

Assuming PointsList.get(i) yields to an Integer, you can sort the user maps with a specific Comparator and Collections.sort(...), e.g.

    ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(NUMBER_OF_SHOWING_USERS);
    for(int i=0;i< NUMBER_OF_SHOWING_USERS; i++) {
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put(ATTRIBUTE_NAME_TEXT_NAME, FriendNames.get(i));
        m.put(ATTRIBUTE_NAME_TEXT_RAITING, PointsList.get(i));
        m.put(ATTRIBUTE_NAME_IMAGE, PhotoAsBytesList.get(i));
        data.add(m);
    }
    // Sorting on user rating
    Collections.sort(data, new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            Integer r1 = (Integer)o1.get(ATTRIBUTE_NAME_TEXT_RAITING);
            Integer r2 = (Integer)o2.get(ATTRIBUTE_NAME_TEXT_RAITING);
            return r1.compareTo(r2);
        }
    });

With some sample data like:

static int NUMBER_OF_SHOWING_USERS = 7;
static String ATTRIBUTE_NAME_TEXT_NAME = "name";
static String ATTRIBUTE_NAME_TEXT_RAITING = "rating";
static String ATTRIBUTE_NAME_IMAGE = "image";
static List<Integer> PointsList = Arrays.asList(2, 3, 1, 5, 7, 2, 3);
static List<String> FriendNames = Arrays.asList("Joe", "Jack", "Averell", "William", "Luck", "Ma", "Rantanplan");
static List<Byte[]> PhotoAsBytesList = Collections.nCopies(FriendNames.size(), (Byte[])null);

System.out.println(data) gives before sorting

[{image=null, name=Joe, rating=2},
{image=null, name=Jack, rating=3},
{image=null, name=Averell, rating=1},
{image=null, name=William, rating=5},
{image=null, name=Luck, rating=7},
{image=null, name=Ma, rating=2},
{image=null, name=Rantanplan, rating=3}]

After sorting

[{image=null, name=Averell, rating=1},
{image=null, name=Joe, rating=2},
{image=null, name=Ma, rating=2},
{image=null, name=Jack, rating=3},
{image=null, name=Rantanplan, rating=3},
{image=null, name=William, rating=5},
{image=null, name=Luck, rating=7}]

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32