There are lots of programming languages in the world today, and some of them are quiet popular. Each language has their own features, syntax and rules. There is one method of programming called functional programming, where you declare what do you need rather then how do you do it. Lots of languages has these features, for example python, bash, c#. In spite of being one of the most popular languages, java has been behind in putting stream processing and lambda expressions into itself for almost four years and finally it did it.
Below are some of the code examples of stream processing and lambda expressions combined that, if you were unfamiliar with it, you will be blown away.
Enjoy!!
Below are some of the code examples of stream processing and lambda expressions combined that, if you were unfamiliar with it, you will be blown away.
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.BiFunction; import java.util.stream.Collectors; public class BiFunctionExample { public static void main(String[] args) { biFunctionStringConcat(); biFunctionExample(); byFunctionFilterExample(); } public static void byFunctionFilterExample(){ List<Double> lst = new ArrayList<Double>(); lst.add(2d); lst.add(200d); lst.add(6d); lst.add(60d); lst.add(122d); lst.add(876d); lst.add(738d); lst.add(333d); lst.add(112d); lst.add(98d); lst.add(0d); lst.add(3d); lst.add(1d); lst.add(6666d); List<Double> resultList = lst.stream() .sorted() .filter( x -> x > 20d ) .collect(Collectors.toList()); Double sumResultList = resultList.stream().reduce(0d, Double::sum); Double max = resultList.stream().max(Comparator.comparing(x -> x)).get(); String plusItems = resultList.stream() .map(x -> x.toString()) .reduce((x, y) -> x + " + " + y) .get(); System.out.println(resultList); System.out.println(plusItems); System.out.println("Sum = " + sumResultList); System.out.println("max = " + max); } public static void biFunctionExample() { BiFunction<Double, Double, List<Double>> bi = (x,y) -> { List<Double> list = new ArrayList<Double>(); list.add(Math.pow(x, y)); list.add(x * y); return list; }; System.out.println(bi.apply(2d, 3d)); } public static void biFunctionStringConcat(){ BiFunction<String, String,String> bi = (x, y) -> { return x + y; }; System.out.println(bi.apply("rajan", " upadhyay")); } }
Enjoy!!