##Functional interface An interface with a single abstract method.
Last active
April 24, 2018 04:41
-
-
Save ranraj/549429fc6953c5c81719659aa201bf73 to your computer and use it in GitHub Desktop.
Java8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran.stream; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class CollectorsTest { | |
public static void main(String[] args) { | |
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); | |
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); | |
System.out.println("Filtered List: " + filtered); | |
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); | |
System.out.println("Merged String: " + mergedString); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Map.Entry; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class FindDuplicate { | |
public static void main(String[] args) throws Exception { | |
List<Item> items = new ArrayList<>(); | |
items.add(new Item("101","Ran")); | |
items.add(new Item("101","Ran")); | |
items.add(new Item("102","Ran")); | |
items.add(new Item("102","Ran")); | |
items.add(new Item("103","Ran")); | |
Stream<Entry<String, List<Item>>> duplicates = items.stream().collect(Collectors.groupingBy(Item::getId)).entrySet().stream().filter(e -> e.getValue().size() > 1); | |
duplicates.forEach( a -> System.out.println(a.getKey())); | |
} | |
} | |
class Item { | |
private String id; | |
private String attribute; | |
public Item(String id,String attr) { | |
this.id = id; | |
this.attribute = attr; | |
} | |
public String getId() { | |
return id; | |
} | |
public void setId(String id) { | |
this.id = id; | |
} | |
public String getAttribute() { | |
return attribute; | |
} | |
public void setAttribute(String attribute) { | |
this.attribute = attribute; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Flatmap example | |
package com.ran.java8; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
/** | |
* Created by ranjithrajd on 21/7/16. | |
*/ | |
public class FlatMapExample { | |
public static void main(String[] args) { | |
Integer[] aArray = {1,3,5}; | |
Integer[] bArray = {2,4,6}; | |
List<Integer> a = Arrays.asList(aArray); | |
List<Integer> b = Arrays.asList(bArray); | |
List<List<Integer>> l = new ArrayList<>(2); | |
l.add(a); | |
l.add(b); | |
//l.forEach(System.out::println); | |
List<Integer> result = l.stream().flatMap( t -> t.stream()).collect(Collectors.toList()); | |
result.forEach(System.out::println); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Optional class | |
public class OptionalClassExample { | |
public static void main(String[] args) { | |
ArithmeticWithOptional arithmetic1 = (a ,b) -> a + b; | |
//arithmetic1.result(10,null); | |
arithmetic1.result(Optional.ofNullable(10),Optional.ofNullable(20)); | |
//arithmetic1.result(Optional.ofNullable(10),Optional.ofNullable(null)); | |
} | |
} | |
interface ArithmeticWithOptional{ | |
Integer process(Integer a , Integer b); | |
default void result(Optional<Integer> a ,Optional<Integer> b){ | |
if(a.isPresent() && b.isPresent()) { | |
System.out.println("Arithmetic Result = " + process(a.get(),b.get())); | |
} | |
else{ | |
System.out.println("Illegal argument passed"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran; | |
import java.util.ArrayList; | |
import java.util.List; | |
//Runnable, Callable, Comparator, ActionListener | |
public class FISample { | |
public static void main(String[] args) { | |
List<NameValiator> validationRules = new ArrayList<NameValiator>(); | |
validationRules.add(((NameValiator) ((NameVO a) -> !a.getName().equals("")))); | |
validationRules.add(((NameValiator) ((NameVO a) -> (a.getName().length() > 5)))); | |
boolean isAllRulesPassed = rulesValidation(validationRules, new NameVO("")); | |
System.out.println(isAllRulesPassed); | |
isAllRulesPassed = rulesValidation(validationRules, new NameVO("ran")); | |
System.out.println(isAllRulesPassed); | |
isAllRulesPassed = rulesValidation(validationRules, new NameVO("ranjith")); | |
System.out.println(isAllRulesPassed); | |
} | |
private static boolean rulesValidation(List<NameValiator> rules, NameVO name) { | |
for (NameValiator rule : rules) { | |
if (!rule.apply(name)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} | |
class NameVO { | |
private String name; | |
public NameVO(String name) { | |
this.setName(name); | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
} | |
@FunctionalInterface | |
interface NameValiator { | |
boolean apply(NameVO name); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran.java8; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class First { | |
public static void main(String[] args) { | |
Integer[] array = {10,20,30,40,50}; | |
List<Integer> seq = Arrays.asList(array); | |
// Stream filter | |
List<Integer> even = seq.stream().filter(a -> a % 2 ==0).collect(Collectors.toList()); | |
// Method reference | |
even.forEach(System.out::println); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran.stream; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class MapTest { | |
//Comparator sort example | |
public static void main(String[] args) { | |
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); | |
//get list of unique squares | |
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); | |
squaresList.sort((s1,s2)->s1.compareTo(s2)); | |
//squaresList.stream().sorted().forEach(System.out::println); | |
squaresList.forEach(System.out::println); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Higher order functions | |
public class HigherOrderFunctions { | |
public static void main(String[] args) { | |
Integer result = isPositive(-3,a -> a > 0).apply(3); | |
System.out.println(result); | |
} | |
private static Function<Integer,Integer> isPositive(Integer i,Predicate<Integer> predicate) { | |
if(predicate.test(i)){ | |
//Lexical scope | |
return (a) -> a * i ; | |
}else{ | |
return a -> a; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran.stream; | |
import java.util.Random; | |
public class StreamRandom { | |
public static void main(String[] args) { | |
Random random = new Random(); | |
//random.ints().distinct().limit(10).forEach(System.out::println); | |
random.ints().forEach(System.out::println); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//stream skip , limit and distinct | |
public class StreamSample1 { | |
public static void main(String[] args) { | |
Integer[] array = {10,20,10,40,50,40}; | |
List<Integer> seq = Arrays.asList(array); | |
// Stream filter - moving predicate | |
Predicate<Integer> isEven = a -> a % 2 == 0; | |
Function<Integer,Integer> shortResult = a -> a / 10; | |
List<Integer> even = seq | |
.stream() | |
.filter(isEven) | |
.map(shortResult) // Make shorter value | |
.distinct() // Distinct result | |
.limit(3) // Takes only first 3 elements | |
.skip(2) // Skip the first 2 element | |
.collect(Collectors.toList()); | |
// Method reference | |
even.forEach(System.out::println); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//mapToDouble example | |
public class StreamSample2 { | |
public static void main(String[] args) { | |
List<SaleOrder> saleOrders = new ArrayList<>(4); | |
saleOrders.add(new SaleOrder(10,"Pen")); | |
saleOrders.add(new SaleOrder(20,"Pencile")); | |
saleOrders.add(new SaleOrder(40,"Ball")); | |
Double amount = saleOrders.stream().mapToDouble(SaleOrder::getAmount).sum(); | |
System.out.println(amount); | |
} | |
} | |
class SaleOrder { | |
private double amount; | |
private String item; | |
public SaleOrder(double amount,String item){ | |
this.amount = amount; | |
this.item = item; | |
} | |
public String getItem() { | |
return item; | |
} | |
public double getAmount() { | |
return amount; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//stream all or none match | |
public class StreamSample3 { | |
public static void main(String[] args) { | |
List<SaleOrder> saleOrders = new ArrayList<>(4); | |
saleOrders.add(new SaleOrder(10,"Pen")); | |
saleOrders.add(new SaleOrder(20,"Pencile")); | |
saleOrders.add(new SaleOrder(40, "Ball")); | |
Boolean result1 = saleOrders.stream().allMatch( a -> a.getAmount() % 2 ==0); | |
System.out.println(result1); | |
Boolean result2 = saleOrders.stream().noneMatch(a -> a.getAmount() % 2 != 0); | |
System.out.println(result2); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ran.stream; | |
import java.util.Arrays; | |
import java.util.IntSummaryStatistics; | |
import java.util.List; | |
public class SummaryStatistics { | |
public static void main(String[] args) { | |
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); | |
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); | |
System.out.println("Highest number in List : " + stats.getMax()); | |
System.out.println("Lowest number in List : " + stats.getMin()); | |
System.out.println("Sum of all numbers : " + stats.getSum()); | |
System.out.println("Average of all numbers : " + stats.getAverage()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Single method interface | |
//Default methods | |
public class InterfaceDefaultMethods { | |
public static void main(String[] args) { | |
Arithmetic arithmetic1 = (a ,b) -> a + b; | |
Arithmetic arithmetic2 = (a ,b) -> a * b; | |
arithmetic1.result(10,20); | |
arithmetic2.result(10,20); | |
} | |
} | |
interface Arithmetic{ | |
Integer process(Integer a , Integer b); | |
default void result(Integer a ,Integer b){ | |
System.out.println("Arithmetic Result = "+process(a,b)); | |
} | |
} |
//map : Making short result
List even = seq
.stream()
.filter(isEven)
.map( a -> a / 10) // Make shorter value
.collect(Collectors.toList());
//Moving to Functions
Function<Integer,Integer> shortResult = a -> a / 10;
List even = seq
.stream()
.filter(isEven)
.map(shortResult) // Make shorter value
.collect(Collectors.toList());
//Higher order functions
isPositive(-3,a -> a > 0);
private static void isPositive(Integer i,Predicate predicate){
if(predicate.test(i)){
System.out.println("Positive Integer");
}else{
System.out.println("Negative Integer");
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//Moving to predicate
Predicate isEven = a -> a % 2 == 0;
List even = seq.stream().filter(isEven).collect(Collectors.toList());