Skip to content

Instantly share code, notes, and snippets.

@rakeshhny
Created October 30, 2020 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rakeshhny/2006396f0432569b4dfa49b88d1c355f to your computer and use it in GitHub Desktop.
Save rakeshhny/2006396f0432569b4dfa49b88d1c355f to your computer and use it in GitHub Desktop.
MethodReferenceExamples
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LambdasAndMethodReferences.iml" filepath="$PROJECT_DIR$/LambdasAndMethodReferences.iml" />
</modules>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="afa15c56-5ecd-4e9e-9377-60b823609329" name="Default Changelist" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="ProjectId" id="1hr944ls26tPugE9O7sUqKvuQSS" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showExcludedFiles" value="true" />
<option name="showLibraryContents" value="true" />
<option name="showMembers" value="true" />
</component>
<component name="PropertiesComponent">
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="settings.editor.selected.configurable" value="editor.preferences.fonts.default" />
</component>
<component name="RunManager" selected="Application.ConstructorReferenceWithMoreArgs">
<configuration name="BoundedMethodReferenceExample" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="BoundedMethodReferenceExample" />
<module name="LambdasAndMethodReferences" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ConstructorReferenceWithMoreArgs" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="ConstructorReferenceWithMoreArgs" />
<module name="LambdasAndMethodReferences" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Example2" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="Example2" />
<module name="LambdasAndMethodReferences" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Example3LongClassName" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="Example3LongClassName" />
<module name="LambdasAndMethodReferences" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="UnboundInstanceMethodReferenceExample" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="UnboundInstanceMethodReferenceExample" />
<module name="LambdasAndMethodReferences" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.ConstructorReferenceWithMoreArgs" />
<item itemvalue="Application.Example3LongClassName" />
<item itemvalue="Application.UnboundInstanceMethodReferenceExample" />
<item itemvalue="Application.BoundedMethodReferenceExample" />
<item itemvalue="Application.Example2" />
</list>
</recent_temporary>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="afa15c56-5ecd-4e9e-9377-60b823609329" name="Default Changelist" comment="" />
<created>1600758150004</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1600758150004</updated>
</task>
<servers />
</component>
<component name="WindowStateProjectService">
<state width="1899" height="666" key="GridCell.Tab.0.bottom" timestamp="1604036502302">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state width="1899" height="348" key="GridCell.Tab.0.bottom/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="666" key="GridCell.Tab.0.bottom/0.0.1920.1040@0.0.1920.1040" timestamp="1604036502302" />
<state width="1899" height="666" key="GridCell.Tab.0.center" timestamp="1604036502301">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state width="1899" height="348" key="GridCell.Tab.0.center/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="666" key="GridCell.Tab.0.center/0.0.1920.1040@0.0.1920.1040" timestamp="1604036502301" />
<state width="1899" height="666" key="GridCell.Tab.0.left" timestamp="1604036502301">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state width="1899" height="348" key="GridCell.Tab.0.left/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="666" key="GridCell.Tab.0.left/0.0.1920.1040@0.0.1920.1040" timestamp="1604036502301" />
<state width="1899" height="666" key="GridCell.Tab.0.right" timestamp="1604036502301">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state width="1899" height="348" key="GridCell.Tab.0.right/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="666" key="GridCell.Tab.0.right/0.0.1920.1040@0.0.1920.1040" timestamp="1604036502301" />
<state width="1899" height="348" key="GridCell.Tab.1.bottom" timestamp="1603983929774">
<screen x="0" y="0" width="1366" height="728" />
</state>
<state width="1899" height="348" key="GridCell.Tab.1.bottom/0.0.1366.728@0.0.1366.728" timestamp="1603983929774" />
<state width="1899" height="348" key="GridCell.Tab.1.bottom/0.0.1920.1040@0.0.1920.1040" timestamp="1603958482619" />
<state width="1899" height="348" key="GridCell.Tab.1.center" timestamp="1603983929773">
<screen x="0" y="0" width="1366" height="728" />
</state>
<state width="1899" height="348" key="GridCell.Tab.1.center/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="348" key="GridCell.Tab.1.center/0.0.1920.1040@0.0.1920.1040" timestamp="1603958482619" />
<state width="1899" height="348" key="GridCell.Tab.1.left" timestamp="1603983929773">
<screen x="0" y="0" width="1366" height="728" />
</state>
<state width="1899" height="348" key="GridCell.Tab.1.left/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="348" key="GridCell.Tab.1.left/0.0.1920.1040@0.0.1920.1040" timestamp="1603958482619" />
<state width="1899" height="348" key="GridCell.Tab.1.right" timestamp="1603983929773">
<screen x="0" y="0" width="1366" height="728" />
</state>
<state width="1899" height="348" key="GridCell.Tab.1.right/0.0.1366.728@0.0.1366.728" timestamp="1603983929773" />
<state width="1899" height="348" key="GridCell.Tab.1.right/0.0.1920.1040@0.0.1920.1040" timestamp="1603958482619" />
<state x="461" y="162" key="SettingsEditor" timestamp="1603184470996">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state x="461" y="162" key="SettingsEditor/0.0.1920.1040@0.0.1920.1040" timestamp="1603184470996" />
<state x="0" y="0" key="com.intellij.ide.util.TipDialog" timestamp="1604035057358">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state x="0" y="0" key="com.intellij.ide.util.TipDialog/0.0.1920.1040@0.0.1920.1040" timestamp="1604035057358" />
<state x="623" y="225" width="672" height="678" key="search.everywhere.popup" timestamp="1603955259405">
<screen x="0" y="0" width="1920" height="1040" />
</state>
<state x="623" y="225" width="672" height="678" key="search.everywhere.popup/0.0.1920.1040@0.0.1920.1040" timestamp="1603955259405" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Bounded instance method reference example.
* Static method reference example.
* Bounded instance method references are similar to static method references.
*/
public class BoundedMethodReferenceExample {
public static void main(String[] args) {
// Program - Parse list of integers in string into a list of integer
List<String> intStringList = Arrays.asList("1","2","3","4","5","6");
// static method reference example
// No. of arguments to the method reference (Integer.parseInt(arg)) are same as
// the num of arguments to function object (Function.apply(arg))
List<Integer> intList = intStringList.stream().map(Integer::parseInt).collect(Collectors.toList());
// bounded instance method reference example
// Num of arguments to the method referenced(println(arg)) are same as
// the num of arguments to the function object (Consumer.accept(arg))
intStringList.forEach(System.out::println);
// static method reference example
// Num of arguments to the method referenced(sum(arg1,arg2)) are same as
// the num of arguments to the function object (BiFunction.apply(arg1, arg2))
Integer sum = intList.stream().reduce(Integer::sum).get();
}
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Supplier;
/**
* Constructor reference example.
* It covers 2 types of constructor reference
* 1) Class Constructor
* 2) Array Constructor
*/
public class ConstructorReferenceExample {
public static void main(String[] args) {
// Class Constructor reference
// Be mindful that Class::new will resolve to a functional interface and do not
// misunderstand this with Class ref = Class::new; This won't compile.
Supplier<HashMap<String, String>> mapSupplier = HashMap::new;
Supplier<HashSet<String>> setSupplier = HashSet::new;
// Array Constructor reference
ArrayConstruction<String> stringArrayConstruction = String[]::new;
ArrayConstruction<Integer> integerArrayConstruction = Integer[]::new;
}
}
@FunctionalInterface
interface ArrayConstruction<T> {
T[] accept(int l);
}
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* Use Constructor Reference to create an instance of a class
* who has parametrized constructor.
*/
public class ConstructorReferenceWithMoreArgs {
public static void main(String[] args) {
Function<String, Student> studentFactory1 = Student::new;
Function<String, Student> studentFactory1Equivalent = fname -> new Student(fname);
BiFunction<String, String, Student> studentFactory2 = Student::new;
BiFunction<String, String, Student> studentFactory2Equivalent = (fname, lname) -> new Student(fname, lname);
}
}
class Student {
public final String fname;
public final String lname;
public Student(String name) {
System.out.println("Using one arg constructor.");
this.fname = name;
this.lname = "last name";
}
public Student(String fname, String lname) {
System.out.println("Using two args constructor.");
this.fname = fname;
this.lname = lname;
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Sort list of String in order of string's length
*/
public class Example1 {
public static void main(String[] args) {
List<String> strings = Arrays.asList("thane","mulund","bhandup","cst","parel","sion");
System.out.println("Before sorting\n" + strings);
Collections.sort(strings);
System.out.println("After sorting\n" + strings);
//-------------------------------------------------------
// Anonymous class instance as a "function object"
// Comparator represents an abstract strategy for sorting and function object provides
// concrete strategy for sorting. (Strategy Design Pattern)
// Collections.sort(strings, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// return Integer.compare(o1.length(), o2.length());
// }
// });
//
// System.out.println("After sorting using function object\n" + strings);
//--------------------------------------------------------
// Using Lambda expression as a function object (Replaces anonymous class)
// Collections.sort(strings, (String s1, String s2) -> Integer.compare(s1.length(), s2.length()));
// Collections.sort(strings, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
// Unbounded instance method reference String::length
// The return type of
// String.length()
// matches the return of
// ToIntFunction.applyAsInt(...)
// Collections.sort(strings, Comparator.comparingInt(String::length));
// strings.sort(Comparator.comparingInt(String::length));
//
// System.out.println("After sorting using lambda expression\n" + strings);
}
}
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Count occurrences of each word in list
*/
public class Example2 {
public static void main(String[] args) {
List<String> words = Arrays.asList("word2","word3","word2","word3","word1","word3");
Map<String, Integer> resultMap = new HashMap<>();
words.forEach(word -> resultMap.merge(word,1, (count, incr) -> count + incr));
// FYI - merge(...) method was added to the Map interface in Java 8
System.out.println("Result1 = \n" + resultMap);
// The code above looks clean but still there is some boilerplate.
// The words count and incr does not add much value and take a lot of horizontal space.
// All we know is that the lambda returns the sum of 2 arguments supplied.
// As of Java 8 all the boxed numerical primitive classes are having static sum method which does exactly the same
// thing. We will leverage this method below.
// With less visual clutter
Map<String, Integer> resultMap2 = new HashMap<>();
words.forEach(word -> resultMap2.merge(word, 1, Integer::sum));
System.out.println("Result2 = \n" + resultMap2);
// Integer::sum -> Takes 2 arguments are returns an Integer
// which is same as
// lambda expression which takes 2 arguments are returns an Integer.
}
}
public class Example3LongClassName {
public static void main(String[] args) {
// calling the method of the same class using
// a method reference
Thread ref1 = new Thread(Example3LongClassName::action);
// calling the method of the same class using
// a lambda expression
Thread ref2 = new Thread(() -> action());
ref1.start();
ref2.start();
// The latter approach using lambda is more succinct than method reference.
}
static void action() {
System.out.println("This is an action");
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Unbounded instance method reference example
*/
public class UnboundInstanceMethodReferenceExample {
public static void main(String[] args) {
// 1) Convert a list of String from lowercase strings to uppercase strings
List<String> stringsLowerCase = Arrays.asList("java","python","html","perl","react","haskell");
System.out.println("String Lower Case = " + stringsLowerCase);
List<String> stringsUpperCase = stringsLowerCase.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());
// The above statement can be rewritten using an unbounded instance method reference like below
stringsUpperCase = stringsLowerCase.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println("String Upper Case = " + stringsUpperCase);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment