Issue
I was solving problems in geeksforgeeks and suddenly got this. I understand the use of "Integer.compare" but could not get the use of "->" in the sortBySetBitCount method.
static void sortBySetBitCount(Integer arr[], int n)
{
Arrays.sort(arr, (a, b) -> Integer.compare(countSetBit(b), countSetBit(a)));
//I mean here the "->" operator
}
static int countSetBit(int n) {
int count = 0;
while (n>0) {
n = n & (n - 1);
count += 1;
}
return count;
}
Solution
Lambda expressions are added in Java 8 and provide below functionalities.
Enable to treat functionality as a method argument, or code as data.
A function that can be created without belonging to any class.
A lambda expression can be passed around as if it was an object and executed on demand.
Syntax:
lambda operator -> body
where lambda operator can be:
Zero parameter:
() -> System.out.println("Zero parameter lambda");
One parameter:–
(p) -> System.out.println("One parameter: " + p);
It is not mandatory to use parentheses, if the type of that variable can be inferred from the context
Multiple parameters :
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " +
p2);
Source for above examples GeeksForGeeks.
import java.util.*;
class MainClass{
public static void main(String ... $){
var out = System.out;
Integer arr[] = {10, 32, 31};
sortBySetBitCount(arr);
//output is 31, 10, 32
//31 has 5 set bits
//10 has 3 set bits
//32 has 1 set bit
out.println(Arrays.asList(arr));
}
static void sortBySetBitCount(Integer arr[]){
//first argument is array they we want to sort
//second argument is a lambda method
Arrays.sort(arr, (a, b) -> Integer.compare(countSetBit(b), countSetBit(a)));
}
//Returns numbers of bit set
static int countSetBit(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count += 1;
}
return count;
}
}
output:
$ javac MainClass.java && java MainClass
[31, 10, 32]
More about lambda methods:
Answered By - Dev Parzival
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.