0

I am using Java -7. I want some help cause i stuck, i have a list that i add values all the time but in the end i want get the latest 15. The list handles DonateTable class that contains .getTime() which return long (System.getCurrentMilliseconds)

and i want to use this value to get the latest top 15. So higher ms = latest value. But idk how. This is my code

public ArrayList<DonateTable> getLog(int objectId)
{
    ArrayList<DonateTable> data = new ArrayList<>();

    for (DonateTable dt : list)
        if (dt.getObjectId() == objectId)
            data.add(dt);

    return data;
}

public static class DonateTable
    {
        int _objectId = 0;
        String _service = "";
        long _time, _points = 0;

        public DonateTable(int ObjectId, String service, long time, long points)
        {
            _objectId = ObjectId;
            _service = service;
            _time = time;
            _points = points;
        }

        public int getObjectId()
        {
            return _objectId;
        }

        public String getService()
        {
            return _service;
        }

        public long getTime()
        {
            return _time;
        }

        public long getPoints()
        {
            return _points;
        }
    }
davidxxx
  • 125,838
  • 23
  • 214
  • 215
magneto30
  • 19
  • 3

1 Answers1

0

You could use a Comparator for DonateTable class and use the getTime() value to sort instances of it.

public class DonateTableByHighestTimeComparator implements Comparator<DonateTable>{

      public int compare(DonateTable o1, DonateTable o2){
         return - Long.compare(o1.getTime(), o2.getTime());
      }
    }

You can use this comparator in this way :

List<DonateTable> data = new ArrayList<>();
...
Collections.sort(data, new DonateTableByHighestTimeComparator());

And at last you can get a sublist view of the first 15 elements of the sorted list :

List<DonateTable> top15Elements = data.subList(0,15);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • and how to implement it, im confused. Like ur class simply compare the values taken from 2 elements but how it works with all elements and gives top 15? ps thanks for answer tho – magneto30 May 15 '17 at 09:47
  • You provide the comparator and the list to the `Collections.sort(List list, Comparator super T> c)` static method. – davidxxx May 15 '17 at 09:48
  • Nop it didn't work in the "game" i make.. I did it this way you show me sir. https://pastebin.com/Vpp0QbaX – magneto30 May 15 '17 at 09:59
  • Indeed. I had used the minus sign in the comparator to reverse the natural order of long comparator as you want to order them by highest (reverse natural order) – davidxxx May 15 '17 at 10:04