|
| 1 | +package com.javatechie.stream; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.function.BiFunction; |
| 7 | +import java.util.function.Function; |
| 8 | +import java.util.stream.Collectors; |
| 9 | +import java.util.stream.Stream; |
| 10 | + |
| 11 | +public class BiFunctionExample implements BiFunction<List<Integer>, List<Integer>, List<Integer>> { |
| 12 | + @Override |
| 13 | + public List<Integer> apply(List<Integer> list1, List<Integer> list2) { |
| 14 | + return Stream.of(list1, list2) |
| 15 | + .flatMap(List::stream) |
| 16 | + .distinct() |
| 17 | + .collect(Collectors.toList()); |
| 18 | + } |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + BiFunction biFunction = new BiFunctionExample(); |
| 22 | + List<Integer> list1 = Stream.of(1, 3, 4, 6, 7, 9, 19).collect(Collectors.toList()); |
| 23 | + List<Integer> list2 = Stream.of(11, 3, 43, 6, 7, 19).collect(Collectors.toList()); |
| 24 | + System.out.println("Traditional approach : " + biFunction.apply(list1, list2)); |
| 25 | + |
| 26 | + BiFunction<List<Integer>,List<Integer>,List<Integer>> biFunction1=new BiFunction<List<Integer>, List<Integer>, List<Integer>>() { |
| 27 | + @Override |
| 28 | + public List<Integer> apply(List<Integer> l1, List<Integer> l2) { |
| 29 | + return Stream.of(l1, l2) |
| 30 | + .flatMap(List::stream) |
| 31 | + .distinct() |
| 32 | + .collect(Collectors.toList()); |
| 33 | + } |
| 34 | + }; |
| 35 | + |
| 36 | + System.out.println("annonymous impl : "+biFunction1.apply(list1, list2)); |
| 37 | + |
| 38 | + |
| 39 | + BiFunction<List<Integer>,List<Integer>,List<Integer>> biFunction2=( l1, l2) ->{ |
| 40 | + return Stream.of(l1, l2) |
| 41 | + .flatMap(List::stream) |
| 42 | + .distinct() |
| 43 | + .collect(Collectors.toList()); |
| 44 | + }; |
| 45 | + |
| 46 | + Function<List<Integer>,List<Integer>> sortedFunction=(lists)->lists |
| 47 | + .stream() |
| 48 | + .sorted() |
| 49 | + .collect(Collectors.toList()); |
| 50 | + |
| 51 | + System.out.println("Lambda approach : "+biFunction2.andThen(sortedFunction).apply(list1, list2)); |
| 52 | + |
| 53 | + |
| 54 | + Map<String, Integer> map=new HashMap<>(); |
| 55 | + map.put("basant",5000); |
| 56 | + map.put("santosh",15000); |
| 57 | + map.put("javed",12000); |
| 58 | + |
| 59 | + BiFunction<String,Integer,Integer> increaseSalaryBiFunction= new BiFunction<String, Integer, Integer>() { |
| 60 | + @Override |
| 61 | + public Integer apply(String key, Integer value) { |
| 62 | + return value+1000; |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + //map.replaceAll(increaseSalaryBiFunction); |
| 67 | + |
| 68 | + |
| 69 | + //BiFunction<String,Integer,Integer> increaseSalBiFunction= ( key, value) -> value+2000; |
| 70 | + |
| 71 | + map.replaceAll(( key, value) -> value+2500); |
| 72 | + |
| 73 | + System.out.println(map); |
| 74 | + } |
| 75 | +} |
0 commit comments