Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing in ArrayList based on Ascending Time

My current data structure is as follows:

public class MyDataTemplate {

  long occurenceTime;
  int val1;
  int val2;

  public MyDataTemplate(Long nanoTime, int val1, int val2) {
    this.occurenceTime = nanoTime;
    this.val1 = val1;
    this.val2 = val2;
    }

}

List<MyDataTemplate> myData = new ArrayList <MyDataTemplate>();

The occurenceTime(long) above represents the system time which I obtain in Android using System.nanoTime()

If data arrived sequentially by time, I could have very well used the above data structure to store data as and when it arrives:

newOccurence = new MyDataTemplate(System.nanoTime(), 42, 55)        
myData.add(newOccurence);

However, since data does not arrive sequentially, I may get a new occurrence earlier than an old occurrence.

My task is to ensure that the myData contains data in ascending order of time, irrespective of when it arrives.

How can I ensure that ?

like image 393
bhaskarc Avatar asked May 03 '26 09:05

bhaskarc


1 Answers

Froggy Oat...

I have made an attempt which seems to loosely illustrate a potential "solution:"

public class MainActivity extends AppCompatActivity {

    public class MyDataTemplate {


        long occurenceTime;
        int val1;
        int val2;

        public MyDataTemplate(Long nanoTime, int val1, int val2) {
            this.occurenceTime = nanoTime;
            this.val1 = val1;
            this.val2 = val2;
        }

    }

    class SortByNanoTime implements Comparator<MyDataTemplate> {

        public int compare(MyDataTemplate a, MyDataTemplate b) {
            if (a.occurenceTime < b.occurenceTime)
                return -1;
            else if (a.occurenceTime > b.occurenceTime)
                return +1;
            else
                return 0;
        }
    }

    List<MyDataTemplate> myData = new ArrayList<MyDataTemplate>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myData.add(new MyDataTemplate((long) 30000.2341, 2, 3));
        myData.add(new MyDataTemplate((long) 234234.234, 3, 4));
        myData.add(new MyDataTemplate((long) 11234234.234, 3, 4));
        myData.add(new MyDataTemplate((long) 4.234, 3, 4));

        Collections.sort(myData, new SortByNanoTime());

        for (MyDataTemplate tempVar : myData) {

            Log.i("XXX", "" + tempVar.occurenceTime);

        }


    }
}
like image 139
Nerdy Bunz Avatar answered May 05 '26 23:05

Nerdy Bunz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!