Java :Alternative to lambda expression

Can anyone provide me the alternative statement to the Arrays.sort line that should work with Java 7.
Thanks. :slight_smile:

You can do this by just using a custom Comparator equivalent to the given lambda expression and then apply Arrays.sort method to make it work in Java7.

For example you maybe wanting to do the following after the line

rank2[i] = ((long) rank[i] << 32) + (i + len < n ? rank[i + len] + 1 : 0);

or you create comparator outside, depends upon you.

class MyComparator implements Comparator<Integer> {
    	      private final long[] array;
    	      public MyComparator(long[] array)
    	      {
    	          this.array = array;
    	      }
 
    	      @Override
    	      public int compare(Integer index1, Integer index2)
    	      {
    	          return Long.compare(array[index1],array[index2]);
    	      }
    	  }
 
      MyComparator comp = new MyComparator(rank2);
      Arrays.sort(sa, comp);

See this working alternative approach on IDEONE Java7.

See these links at stackoverflow for more information.

http://stackoverflow.com/questions/21970719/java-arrays-sort-with-lambda-expression

http://stackoverflow.com/questions/5898690/java-sort-array1-based-on-array2

http://stackoverflow.com/questions/18129807/in-java-how-do-you-sort-one-list-based-on-another

You may also want @betlista :diamonds::diamonds: to answer/comment here, he is very good in general and exceptional in java. He may provide some better idea(s) regarding this and lambda expressions indroduced in Java8.

using Integer instead of int will cost you extra time. Autoboxing/unboxing…you can implement it easily with primitives.

@rohanagarwal

You are right and I am aware of it, but compareTo() has problems with primitive datatypes.

For performance enhancement check http://stackoverflow.com/questions/9150446/compareto-with-primitives-integer-int and this.

Also didn’t want to complicate things with boxing/unboxing for the OP. :slight_smile: