Calculate the difference between the elements in a list











up vote
1
down vote

favorite












overview



So I have two lists which have the same size. One is called roadS and the second one is called simTime. My aim is to calculate the difference between two indexes which lie next to each other and divide them with the difference of the other list. On the picture above you see what I mean.



This is my current function:



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS){
List<Double> speedS = new ArrayList<>();
for(int idx = 1; idx < roadS.size();idx++){
double curSpeedS = (roadS.get(idx)-roadS.get(idx-1))/(simTime.get(idx)-simTime.get(idx-1));
speedS.add(curSpeedS);
}
return speedS;
}


Now although the function is quite short, I aim to find a better or faster solution.



For eg. in phyton you could you pantas library and do this:



player.df['speedS'] = player.df.roadS.diff().shift(-1) / player.df.simTime.diff().shift(-1)     


My aim is to solve this problem more efficient. Does Java or another library maybe provide such functions where I can for calculate the differences










share|improve this question














bumped to the homepage by Community 26 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
    – Gregor Ophey
    Aug 23 at 10:41















up vote
1
down vote

favorite












overview



So I have two lists which have the same size. One is called roadS and the second one is called simTime. My aim is to calculate the difference between two indexes which lie next to each other and divide them with the difference of the other list. On the picture above you see what I mean.



This is my current function:



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS){
List<Double> speedS = new ArrayList<>();
for(int idx = 1; idx < roadS.size();idx++){
double curSpeedS = (roadS.get(idx)-roadS.get(idx-1))/(simTime.get(idx)-simTime.get(idx-1));
speedS.add(curSpeedS);
}
return speedS;
}


Now although the function is quite short, I aim to find a better or faster solution.



For eg. in phyton you could you pantas library and do this:



player.df['speedS'] = player.df.roadS.diff().shift(-1) / player.df.simTime.diff().shift(-1)     


My aim is to solve this problem more efficient. Does Java or another library maybe provide such functions where I can for calculate the differences










share|improve this question














bumped to the homepage by Community 26 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
    – Gregor Ophey
    Aug 23 at 10:41













up vote
1
down vote

favorite









up vote
1
down vote

favorite











overview



So I have two lists which have the same size. One is called roadS and the second one is called simTime. My aim is to calculate the difference between two indexes which lie next to each other and divide them with the difference of the other list. On the picture above you see what I mean.



This is my current function:



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS){
List<Double> speedS = new ArrayList<>();
for(int idx = 1; idx < roadS.size();idx++){
double curSpeedS = (roadS.get(idx)-roadS.get(idx-1))/(simTime.get(idx)-simTime.get(idx-1));
speedS.add(curSpeedS);
}
return speedS;
}


Now although the function is quite short, I aim to find a better or faster solution.



For eg. in phyton you could you pantas library and do this:



player.df['speedS'] = player.df.roadS.diff().shift(-1) / player.df.simTime.diff().shift(-1)     


My aim is to solve this problem more efficient. Does Java or another library maybe provide such functions where I can for calculate the differences










share|improve this question













overview



So I have two lists which have the same size. One is called roadS and the second one is called simTime. My aim is to calculate the difference between two indexes which lie next to each other and divide them with the difference of the other list. On the picture above you see what I mean.



This is my current function:



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS){
List<Double> speedS = new ArrayList<>();
for(int idx = 1; idx < roadS.size();idx++){
double curSpeedS = (roadS.get(idx)-roadS.get(idx-1))/(simTime.get(idx)-simTime.get(idx-1));
speedS.add(curSpeedS);
}
return speedS;
}


Now although the function is quite short, I aim to find a better or faster solution.



For eg. in phyton you could you pantas library and do this:



player.df['speedS'] = player.df.roadS.diff().shift(-1) / player.df.simTime.diff().shift(-1)     


My aim is to solve this problem more efficient. Does Java or another library maybe provide such functions where I can for calculate the differences







java performance calculator






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Aug 23 at 7:51









plshm

285




285





bumped to the homepage by Community 26 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 26 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
    – Gregor Ophey
    Aug 23 at 10:41


















  • To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
    – Gregor Ophey
    Aug 23 at 10:41
















To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
– Gregor Ophey
Aug 23 at 10:41




To increase efficiency of adding elements to the result, allocate it with the proper size, here new List<Double> speedS = ArrayList<>(simTime.size() -1);
– Gregor Ophey
Aug 23 at 10:41










3 Answers
3






active

oldest

votes

















up vote
0
down vote













To simplify speed collection creation logic you can replace actual values in roadS and simTime with the corresponding differences, e.g.:

roadS = {2, 0, 2, 1}
simTime= {3, 1, 1, 1}


Then you can use one of the examples provided here.

For example in Java 8:



double roadS = {2, 0, 2, 1};
double simTime = {3, 1, 1, 1};

double c = IntStream.range(0, roadS.length)
.mapToDouble(i -> roadS[i] / simTime[i])
.toArray();





share|improve this answer























  • range does not exist for DoubleStream
    – plshm
    Aug 23 at 9:23






  • 1




    That should probably be IntStream and mapToDouble
    – mtj
    Aug 23 at 9:58










  • @mtj, thanks for your contribution, edited my answer :)
    – Alexey Andronov
    Aug 23 at 10:04




















up vote
0
down vote













IMO you code is very clear and therefore easy to understand.



You're comparing the Java code to a Python code which is shorter. But the Python code is using two methods: diff and shift. They provide functionality which you wrote in Java by yourself.



If you're aiming to have a shorter getSpeedS function you can also define a diff function in Java:



protected double diff(List<Double> simTime, List<Double> roadS, int idx) {
return (roadS.get(idx) - roadS.get(idx - 1)) / (simTime.get(idx) - simTime.get(idx - 1));
}


Using the Stream-API you can implement getSpeedS like this:



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
return IntStream.range(0, simTime.size())
.mapToDouble(idx -> diff(simTime, roadS, idx))
.boxed()
.collect(Collectors.toList());
}


And if you write it all in one line ...



public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
return IntStream.range(0, simTime.size()).mapToDouble(idx -> diff(simTime, roadS, idx)).boxed().collect(Collectors.toList());


}



it's not much longer than the Python code. But writing it all in one line is harder to debug. Therefore I prefer the previous version.



Otherwise you could also implement a DoubleList which provides like the Python collection a diff and a shift function.






share|improve this answer




























    up vote
    0
    down vote













    Your implementation is good and easy to understand.



    When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> ($O(n)$ vs. $O(n^2)$ for your getSpeedS).



    If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.



    If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.



    If you need maximum performance, then use arrays (double) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.






    share|improve this answer





















      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "196"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202286%2fcalculate-the-difference-between-the-elements-in-a-list%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      To simplify speed collection creation logic you can replace actual values in roadS and simTime with the corresponding differences, e.g.:

      roadS = {2, 0, 2, 1}
      simTime= {3, 1, 1, 1}


      Then you can use one of the examples provided here.

      For example in Java 8:



      double roadS = {2, 0, 2, 1};
      double simTime = {3, 1, 1, 1};

      double c = IntStream.range(0, roadS.length)
      .mapToDouble(i -> roadS[i] / simTime[i])
      .toArray();





      share|improve this answer























      • range does not exist for DoubleStream
        – plshm
        Aug 23 at 9:23






      • 1




        That should probably be IntStream and mapToDouble
        – mtj
        Aug 23 at 9:58










      • @mtj, thanks for your contribution, edited my answer :)
        – Alexey Andronov
        Aug 23 at 10:04

















      up vote
      0
      down vote













      To simplify speed collection creation logic you can replace actual values in roadS and simTime with the corresponding differences, e.g.:

      roadS = {2, 0, 2, 1}
      simTime= {3, 1, 1, 1}


      Then you can use one of the examples provided here.

      For example in Java 8:



      double roadS = {2, 0, 2, 1};
      double simTime = {3, 1, 1, 1};

      double c = IntStream.range(0, roadS.length)
      .mapToDouble(i -> roadS[i] / simTime[i])
      .toArray();





      share|improve this answer























      • range does not exist for DoubleStream
        – plshm
        Aug 23 at 9:23






      • 1




        That should probably be IntStream and mapToDouble
        – mtj
        Aug 23 at 9:58










      • @mtj, thanks for your contribution, edited my answer :)
        – Alexey Andronov
        Aug 23 at 10:04















      up vote
      0
      down vote










      up vote
      0
      down vote









      To simplify speed collection creation logic you can replace actual values in roadS and simTime with the corresponding differences, e.g.:

      roadS = {2, 0, 2, 1}
      simTime= {3, 1, 1, 1}


      Then you can use one of the examples provided here.

      For example in Java 8:



      double roadS = {2, 0, 2, 1};
      double simTime = {3, 1, 1, 1};

      double c = IntStream.range(0, roadS.length)
      .mapToDouble(i -> roadS[i] / simTime[i])
      .toArray();





      share|improve this answer














      To simplify speed collection creation logic you can replace actual values in roadS and simTime with the corresponding differences, e.g.:

      roadS = {2, 0, 2, 1}
      simTime= {3, 1, 1, 1}


      Then you can use one of the examples provided here.

      For example in Java 8:



      double roadS = {2, 0, 2, 1};
      double simTime = {3, 1, 1, 1};

      double c = IntStream.range(0, roadS.length)
      .mapToDouble(i -> roadS[i] / simTime[i])
      .toArray();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 23 at 10:03

























      answered Aug 23 at 8:41









      Alexey Andronov

      1015




      1015












      • range does not exist for DoubleStream
        – plshm
        Aug 23 at 9:23






      • 1




        That should probably be IntStream and mapToDouble
        – mtj
        Aug 23 at 9:58










      • @mtj, thanks for your contribution, edited my answer :)
        – Alexey Andronov
        Aug 23 at 10:04




















      • range does not exist for DoubleStream
        – plshm
        Aug 23 at 9:23






      • 1




        That should probably be IntStream and mapToDouble
        – mtj
        Aug 23 at 9:58










      • @mtj, thanks for your contribution, edited my answer :)
        – Alexey Andronov
        Aug 23 at 10:04


















      range does not exist for DoubleStream
      – plshm
      Aug 23 at 9:23




      range does not exist for DoubleStream
      – plshm
      Aug 23 at 9:23




      1




      1




      That should probably be IntStream and mapToDouble
      – mtj
      Aug 23 at 9:58




      That should probably be IntStream and mapToDouble
      – mtj
      Aug 23 at 9:58












      @mtj, thanks for your contribution, edited my answer :)
      – Alexey Andronov
      Aug 23 at 10:04






      @mtj, thanks for your contribution, edited my answer :)
      – Alexey Andronov
      Aug 23 at 10:04














      up vote
      0
      down vote













      IMO you code is very clear and therefore easy to understand.



      You're comparing the Java code to a Python code which is shorter. But the Python code is using two methods: diff and shift. They provide functionality which you wrote in Java by yourself.



      If you're aiming to have a shorter getSpeedS function you can also define a diff function in Java:



      protected double diff(List<Double> simTime, List<Double> roadS, int idx) {
      return (roadS.get(idx) - roadS.get(idx - 1)) / (simTime.get(idx) - simTime.get(idx - 1));
      }


      Using the Stream-API you can implement getSpeedS like this:



      public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
      return IntStream.range(0, simTime.size())
      .mapToDouble(idx -> diff(simTime, roadS, idx))
      .boxed()
      .collect(Collectors.toList());
      }


      And if you write it all in one line ...



      public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
      return IntStream.range(0, simTime.size()).mapToDouble(idx -> diff(simTime, roadS, idx)).boxed().collect(Collectors.toList());


      }



      it's not much longer than the Python code. But writing it all in one line is harder to debug. Therefore I prefer the previous version.



      Otherwise you could also implement a DoubleList which provides like the Python collection a diff and a shift function.






      share|improve this answer

























        up vote
        0
        down vote













        IMO you code is very clear and therefore easy to understand.



        You're comparing the Java code to a Python code which is shorter. But the Python code is using two methods: diff and shift. They provide functionality which you wrote in Java by yourself.



        If you're aiming to have a shorter getSpeedS function you can also define a diff function in Java:



        protected double diff(List<Double> simTime, List<Double> roadS, int idx) {
        return (roadS.get(idx) - roadS.get(idx - 1)) / (simTime.get(idx) - simTime.get(idx - 1));
        }


        Using the Stream-API you can implement getSpeedS like this:



        public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
        return IntStream.range(0, simTime.size())
        .mapToDouble(idx -> diff(simTime, roadS, idx))
        .boxed()
        .collect(Collectors.toList());
        }


        And if you write it all in one line ...



        public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
        return IntStream.range(0, simTime.size()).mapToDouble(idx -> diff(simTime, roadS, idx)).boxed().collect(Collectors.toList());


        }



        it's not much longer than the Python code. But writing it all in one line is harder to debug. Therefore I prefer the previous version.



        Otherwise you could also implement a DoubleList which provides like the Python collection a diff and a shift function.






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          IMO you code is very clear and therefore easy to understand.



          You're comparing the Java code to a Python code which is shorter. But the Python code is using two methods: diff and shift. They provide functionality which you wrote in Java by yourself.



          If you're aiming to have a shorter getSpeedS function you can also define a diff function in Java:



          protected double diff(List<Double> simTime, List<Double> roadS, int idx) {
          return (roadS.get(idx) - roadS.get(idx - 1)) / (simTime.get(idx) - simTime.get(idx - 1));
          }


          Using the Stream-API you can implement getSpeedS like this:



          public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
          return IntStream.range(0, simTime.size())
          .mapToDouble(idx -> diff(simTime, roadS, idx))
          .boxed()
          .collect(Collectors.toList());
          }


          And if you write it all in one line ...



          public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
          return IntStream.range(0, simTime.size()).mapToDouble(idx -> diff(simTime, roadS, idx)).boxed().collect(Collectors.toList());


          }



          it's not much longer than the Python code. But writing it all in one line is harder to debug. Therefore I prefer the previous version.



          Otherwise you could also implement a DoubleList which provides like the Python collection a diff and a shift function.






          share|improve this answer












          IMO you code is very clear and therefore easy to understand.



          You're comparing the Java code to a Python code which is shorter. But the Python code is using two methods: diff and shift. They provide functionality which you wrote in Java by yourself.



          If you're aiming to have a shorter getSpeedS function you can also define a diff function in Java:



          protected double diff(List<Double> simTime, List<Double> roadS, int idx) {
          return (roadS.get(idx) - roadS.get(idx - 1)) / (simTime.get(idx) - simTime.get(idx - 1));
          }


          Using the Stream-API you can implement getSpeedS like this:



          public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
          return IntStream.range(0, simTime.size())
          .mapToDouble(idx -> diff(simTime, roadS, idx))
          .boxed()
          .collect(Collectors.toList());
          }


          And if you write it all in one line ...



          public List<Double> getSpeedS(List<Double> simTime, List<Double> roadS) {
          return IntStream.range(0, simTime.size()).mapToDouble(idx -> diff(simTime, roadS, idx)).boxed().collect(Collectors.toList());


          }



          it's not much longer than the Python code. But writing it all in one line is harder to debug. Therefore I prefer the previous version.



          Otherwise you could also implement a DoubleList which provides like the Python collection a diff and a shift function.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 23 at 10:24









          LuCio

          1012




          1012






















              up vote
              0
              down vote













              Your implementation is good and easy to understand.



              When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> ($O(n)$ vs. $O(n^2)$ for your getSpeedS).



              If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.



              If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.



              If you need maximum performance, then use arrays (double) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.






              share|improve this answer

























                up vote
                0
                down vote













                Your implementation is good and easy to understand.



                When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> ($O(n)$ vs. $O(n^2)$ for your getSpeedS).



                If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.



                If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.



                If you need maximum performance, then use arrays (double) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Your implementation is good and easy to understand.



                  When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> ($O(n)$ vs. $O(n^2)$ for your getSpeedS).



                  If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.



                  If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.



                  If you need maximum performance, then use arrays (double) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.






                  share|improve this answer












                  Your implementation is good and easy to understand.



                  When using List<Double> for input data, be sure to use an efficient implementation. Otherwise you could get really bad read performance. E.g., when you access elements by index, ArrayList<Double> will be much faster than LinkedList<Double> ($O(n)$ vs. $O(n^2)$ for your getSpeedS).



                  If you must support arbitrary types of List<Double> you would probably better off when you use Iterators instead of element access by index.



                  If you use an ArrayList and know its final size in advance, always construct it with the capacity needed (new ArrayList<>(size)). This avoids reallocation and copying of the internal array that holds the elements while adding elements.



                  If you need maximum performance, then use arrays (double) instead of lists. For large data sets they can speed up the creation of the input in-memory objects by factors greater than two. Additionally they may give you a significant advantage in read performance due to better utilization of processor caches compared to list implementations.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 22 at 20:24









                  aventurin

                  34519




                  34519






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f202286%2fcalculate-the-difference-between-the-elements-in-a-list%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Feedback on college project

                      Futebolista

                      Albești (Vaslui)