I am new to lambda expressions and I have this code to scan Eddystone beacons and I want to remove the lambda expression from it. I don't know exactly how they work. Can anyone help?
beaconManager.getRegionViewModel(myRegion).getRangedBeacons().observe(this, beacons -> {
noBeacons.setText(String.valueOf(beacons.size()));
for (Beacon beacon : beacons) {
if (uuids.contains(beacon))
continue;
uuids.add(beacon);
if (beacon.getServiceUuid() == 0xfeaa && beacon.getBeaconTypeCode() == 0x00) {
// This is a Eddystone-UID frame
Identifier namespaceId = beacon.getId1();
Identifier instanceId = beacon.getId2();
logthis("I see a beacon transmitting namespace id: " namespaceId
" and instance id: " instanceId
" approximately " beacon.getDistance() " meters away.");
}
}
});
CodePudding user response:
The second parameter of the observe
method is a functional interface, thats why you can put a lambda in it. Most likely it will be Consumer<T>
from the java.util.function package because it takes just one argument beacons
. If you want that lambda removed (i guess you mean replaced) you would need to define a class which implements this functional interface, like:
class Helper implements Consumer<Beacon[]> {
@Override
public void accept(Beacon[] beacons) {
// lambda body here
}
}
and give an instance of the class to observe
:
beaconManager.getRegionViewModel(myRegion).getRangedBeacons().observe(this, new Helper());
You could also do it in a more inline fashion with anonymous interface implementations, like so:
beaconManager.getRegionViewModel(myRegion).getRangedBeacons().observe(this, new Consumer<Beacon[]>() {
public void accept(Beacon[] beacons) {
// lambda body here
}
});
But now you see there is no point in going this detour if not forced (read Java <8).
Just learn a bit lambda syntax which is basically () -> {}
and it does all the hassle for you.