I'm using the for-each construct in Java as follows:
public int getNumRStations() { int numRoutes = 0; for (ArrayList<Route> route : routes) { numRoutes += route.size(); } return numRoutes; }
NetBeans shows a warning/notice that says "Can use functional operations". Upon automatically resolving it, the newly generated code shows this:
public int getNumRStations() { int numRoutes = 0; numRoutes = routes.stream().map((route) -> route.size()).reduce(numRoutes, Integer::sum); return numRoutes; }
Functional interfaces are interfaces that ensure that they include precisely only one abstract method. Functional interfaces are used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method.
Java is a functional style language and the language like Haskell is a purely functional programming language. Let's understand a few concepts in functional programming: Higher-order functions: In functional programming, functions are to be considered as first-class citizens.
Objects are the base of java programming language and we can never have a function without an Object, that's why Java language provide support for using lambda expressions only with functional interfaces.
A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.
That looks like NetBeans suggesting refactoring your sum operation as a Java 8 "lambda" or functional programming operation using the map and reduce functions from the Stream interface. You must be using a Java 8 JDK with NetBeans.
Breaking down what it's doing:
the "map()" function is performing a count of all of your route
sizes in your routes
array list,
the "reduce()" function is then performing a sum of those individual sizes to get the final result for the total number of routes.
The map() and reduce() functions are documented in the Java 8 documentation for the Stream interface available at this link
This answer addresses "what it is" but doesn't address "why it's better". I will admit to still learning about these constructs myself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With