{"id":9355,"date":"2020-04-22T22:55:38","date_gmt":"2020-04-22T17:25:38","guid":{"rendered":"https:\/\/java2blog.com\/?p=9355"},"modified":"2023-11-28T15:10:38","modified_gmt":"2023-11-28T09:40:38","slug":"java-8-method-reference","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-8-method-reference\/","title":{"rendered":"Java 8 Method reference"},"content":{"rendered":"<p><a href=\"https:\/\/java2blog.com\/java-8-tutorial\/\" rel=\"noopener noreferrer\" target=\"_blank\">Java 8<\/a> has introduced a lot of new features such as <a href=\"https:\/\/java2blog.com\/lambda-expressions-in-java-8\/\" rel=\"noopener noreferrer\" target=\"_blank\">lambda expressions<\/a>, stream, Method references etc.<\/p>\n<p>In this post, we will see what are Method references and how can we use it. I will try to provide more examples rather than theory.<br \/>\n<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#1_Introduction_to_Method_Reference\">1. Introduction to Method Reference<\/a><\/li><li><a href=\"#2_Types_of_method_references\">2. Types of method references<\/a><ul><li><a href=\"#21_Reference_to_static_method\">2.1 Reference to static method<\/a><\/li><li><a href=\"#22_Reference_to_instance_method_of_object_type\">2.2 Reference to instance method of object type<\/a><\/li><li><a href=\"#23_Reference_to_instance_method_of_existing_object\">2.3 Reference to instance method of existing object<\/a><\/li><li><a href=\"#24_Reference_constructor\">2.4 Reference constructor<\/a><\/li><\/ul><\/li><li><a href=\"#3_Excercise\">3. Excercise<\/a><ul><li><a href=\"#31_Excercise1\">3.1 Excercise:1<\/a><\/li><li><a href=\"#32_Excercise2\">3.2 Excercise:2<\/a><\/li><li><a href=\"#33_Excercise3\">3.3 Excercise:3<\/a><\/li><\/ul><\/li><li><a href=\"#4_Conclusion\">4. Conclusion<\/a><\/li><\/ul><\/div>\n\n<h2><span id=\"1_Introduction_to_Method_Reference\">1. Introduction to Method Reference<\/span><\/h2>\n<p><code>Method references<\/code> are special types of <a href=\"https:\/\/java2blog.com\/lambda-expressions-in-java-8\/\" rel=\"noopener noreferrer\" target=\"_blank\">lambda expressions<\/a> that execute only one method.<br \/>\n<strong>General syntax of method reference:<\/strong><\/p>\n<pre class=\"lang:java decode:1 \">\nobject::methodName\n<\/pre>\n<p>You might have already guessed that you need to understand lambda expressions first. If you are comfortable with lambda expressions, then let&#8217;s move forward.<\/p>\n<div class=\"content-box-green\">\n<ul>\n<li><a href=\"https:\/\/java2blog.com\/lambda-expressions-in-java-8\/\" rel=\"noopener noreferrer\" target=\"_blank\">Lambda expression in java 8<\/a><\/li>\n<li><a href=\"https:\/\/java2blog.com\/java-8-functional-interface-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">Functional interface in java 8<\/a><\/li>\n<\/ul>\n<\/div>\n<p>Let&#8217;s understand this with the help of example:<\/p>\n<p>Let&#8217;s create class <code>MethodReferecesLambdaExpressionMain<\/code> in which we are going to print list using stream&#8217;s <a href=\"https:\/\/java2blog.com\/java-8-foreach-examples\/\" rel=\"noopener noreferrer\" target=\"_blank\">foreach<\/a> method.<\/p>\n<pre class=\"lang:java mark:18-26,34,43 decode:1 \" title=\"Method reference example\">\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Consumer;\n\npublic class MethodReferecesLambdaExpressionMain {\n\n    public static void main(String args[])\n    {\n        List&lt;String&gt; countryList=Arrays.asList(new String[] {\"India\", \"China\",\"Nepal\",\"Russia\"});\n\n        System.out.println(\"=======================\");\n        System.out.println(\"Using anonymous class\");\n        System.out.println(\"=======================\");\n\n        \/\/ Using anonymous class\n        countryList.stream().forEach(\n                new Consumer&lt;String&gt;() {\n\n                    @Override\n                    public void accept(String country) {\n                        System.out.println(country);    \n                    }\n                });\n\n        System.out.println(\"=======================\");\n        System.out.println(\"Using lambda expression\");\n        System.out.println(\"=======================\");\n\n     \/\/ Using lambda expression\n        countryList.stream().forEach(\n                country -&gt; System.out.println(country)\n                );\n\n        System.out.println(\"=======================\");\n        System.out.println(\"Using Method references\");\n        System.out.println(\"=======================\");\n\n      \/\/ Using method reference\n        countryList.stream().forEach(\n                System.out::println\n            );\n    }   \n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\n=======================\nUsing anonymous class\n=======================\nIndia\nChina\nNepal\nRussia\n=======================\nUsing lambda expression\n=======================\nIndia\nChina\nNepal\nRussia\n=======================\nUsing Method references\n=======================\nIndia\nChina\nNepal\nRussia\n<\/pre>\n<p><code>stream.foreach()<\/code> method takes <a href=\"https:\/\/java2blog.com\/java-8-consumer-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">consumer<\/a> functional interface as agrument.<\/p>\n<p><a href=\"https:\/\/java2blog.com\/java-8-consumer-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">Consumer<\/a> is functional interface that takes a single argument and returns nothing.<br \/>\nWe have used consumer functional interface in 3 ways.<\/p>\n<ol>\n<li>Using anonymous class\n<pre class=\"lang:java decode:1 \" title=\"Consumer Functional Interface\">\n        Consumer<string> consumer1 = new Consumer<string>() {\n\n                    @Override\n                    public void accept(String country) {\n                        System.out.println(country);    \n                    }\n                };\n        <\/string><\/string><\/pre>\n<\/li>\n<li>Using lambda expression\n<pre class=\"lang:java decode:1 \">\nConsumer<string> consumer2 = country -&gt; System.out.println(country);\n<\/string><\/pre>\n<\/li>\n<li>Using method reference\n<pre class=\"lang:java decode:1 \">\nConsumer<string> consumer3 = System.out::println;\n<\/string><\/pre>\n<\/li>\n<\/ol>\n<blockquote><p>You might already know that you can use lambda expression instead of an anonymous class, but You can use method reference only when the lambda expression just calls to a method.<\/p><\/blockquote>\n<p>So if you look at below syntax:<\/p>\n<pre class=\"lang:java decode:1 \">\nConsumer<string> consumer3 = System.out::println;\n<\/string><\/pre>\n<p>In method reference, we have Class or object before <code>::<\/code> and method name after <code>::<\/code> without arguments.<\/p>\n<p><strong>Did you notice the method reference does not have arguments?<\/strong><br \/>\nYes, we don&#8217;t need to pass arguments to method reference, arguments are passed automatically internally based on type of method reference.<\/p>\n<p>The below diagrams will make it clearer.<br \/>\nYou can use method reference as below:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/MethodReference-1024x679.jpg\" alt=\"MethodReference\" width=\"700\" height=\"463\" class=\"aligncenter size-large wp-image-9357\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/MethodReference-1024x679.jpg 1024w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/MethodReference-300x199.jpg 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/MethodReference.jpg 1028w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>Let&#8217;s say you want to convert <code>country<\/code> to <code>uppercase<\/code> before printing it. You can achieve it using <code>anonymous class<\/code> and <code>lambda expression<\/code> but not with method reference.<\/p>\n<p>You can not use method reference as below:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2020\/04\/MethodReferenceNot-1024x760.jpg\" alt=\"MethodReferenceNot\" width=\"700\" height=\"463\" class=\"aligncenter size-large wp-image-9358\" \/><\/p>\n<p>You can obviously use the stream&#8217;s <a href=\"https:\/\/java2blog.com\/java-8-stream-map\/\" rel=\"noopener noreferrer\" target=\"_blank\">map()<\/a> method to convert the <code>country<\/code> to <code>uppercase<\/code> before printing it. I just want to demonstrate when method reference can&#8217;t be used.<\/p>\n<h2><span id=\"2_Types_of_method_references\">2. Types of method references<\/span><\/h2>\n<p>There are four types of method references.<\/p>\n<ol>\n<li>Reference to static method<\/li>\n<li>Reference to instance method of object type<\/li>\n<li>Reference to instance method of existing object<\/li>\n<li>Reference constructor<\/li>\n<\/ol>\n<h3><span id=\"21_Reference_to_static_method\">2.1 Reference to static method<\/span><\/h3>\n<p>When you have lambda expression which calls to static method, then you can method reference to static method.<\/p>\n<p>Lambda expression syntax<br \/>\n<code>(args) -&gt; ClassName.someStaticMethod(args)<\/code><br \/>\ncan be converted to<br \/>\n<code>ClassName::someStaticMethod<\/code><\/p>\n<p>Let&#8217;s see this with the help of example.<\/p>\n<p>Create a class name <code>PowerFunctions<\/code><\/p>\n<pre class=\"lang:java decode:1 \">\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Function;\n\nclass PowerFunctions {\n\n    \/\/ This is the method we will call in method reference\n    public static Integer power(int a)\n    {\n        return a*a;\n    }\n\n    \/\/ Function is functional interface which will be target for method reference\n    public static List&lt;Integer&gt; calculatePowOf2ForList(List&lt;Integer&gt; list,\n                                           Function&lt;Integer,Integer&gt; function)\n    {\n        List&lt;Integer&gt; powerNumbers = new ArrayList&lt;&gt;();\n\n        for(Integer num:list)\n        {\n            Integer powOf2 = function.apply(num);\n            powerNumbers.add(powOf2);\n        }\n        return powerNumbers;\n    }\n\n}\n<\/pre>\n<p><a href=\"https:\/\/java2blog.com\/java-8-function-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">Function<\/a> is functional interface that takes a single input T and returns a single output R.<\/p>\n<p>We can call <code>calculatePowOf2ForList()<\/code> as below:<\/p>\n<pre class=\"lang:java mark:15-22,28,34 decode:1 \">\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Function;\n\npublic class StaticMethodReferenceMain {\n\n    public static void main(String args[])\n    {\n\n        List&lt;Integer&gt; list=Arrays.asList(new Integer[] {1,2,3,4,5});\n\n        \/\/ using anonymous class\n        Function&lt;Integer,Integer&gt; function1=new Function&lt;Integer, Integer&gt;() {\n\n            @Override\n            public Integer apply(Integer num) {\n                return PowerFunctions.power(num);\n            }\n        };\n\n        List&lt;Integer&gt; calculatePowForList1 = PowerFunctions.calculatePowOf2ForList(list, function1); \n        System.out.println(calculatePowForList1);\n\n        \/\/ Using lambda expression\n        Function&lt;Integer,Integer&gt; function2 = (num) -&gt; PowerFunctions.power(num);\n\n        List&lt;Integer&gt; calculatePowForList2 = PowerFunctions.calculatePowOf2ForList(list, function2); \n        System.out.println(calculatePowForList2);\n\n        \/\/ Using Method reference\n        Function&lt;Integer,Integer&gt; function3 = PowerFunctions::power;\n\n        List&lt;Integer&gt; calculatePowForList3 = PowerFunctions.calculatePowOf2ForList(list, function3); \n        System.out.println(calculatePowForList3);\n\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output:<\/p>\n<pre title=\"Output\">\n[1, 4, 9, 16, 25]\n[1, 4, 9, 16, 25]\n[1, 4, 9, 16, 25]\n<\/pre>\n<p>If you notice,<code>Function&lt;Integer,Integer&gt; function2 = (num) -&gt; PowerFunctions.power(num);<\/code> is of type <code>(args) -&gt; className.someStaticMethod(args)<\/code><br \/>\nHere,<\/p>\n<ul>\n<li><code>PowerFunctions<\/code> is className<\/li>\n<li>someStaticMethod is <code>power<\/code> method<\/li>\n<li><code>num<\/code> is power method argument.<\/li>\n<\/ul>\n<p>We are calling a static method <code>power<\/code> of class <code>PowerFunctions<\/code> in lambda expression, that&#8217;s why we can use it as method reference.<\/p>\n<p>So instead of<br \/>\n<code>Function&lt;Integer,Integer&gt; function2 = (num) -&gt; PowerFunctions.power(num);<\/code><br \/>\nwe can use<br \/>\n<code>Function&lt;Integer,Integer&gt; function3 = PowerFunctions::power;<\/code><\/p>\n<p>Here,<\/p>\n<ul>\n<li>First type parameter of <code>Function<\/code>(Integer) is first parameter of static method <code>power()<\/code>.<\/li>\n<li>Second type parameter of <code>Function<\/code>(Integer) is return type of static method <code>power()<\/code>.<\/li>\n<\/ul>\n<h3><span id=\"22_Reference_to_instance_method_of_object_type\">2.2 Reference to instance method of object type<\/span><\/h3>\n<p>When you have lambda expression where instance of object is passed and calls to an instance method with\/without parameters, then you can use method reference to an instance method with object type.<\/p>\n<p>Lambda expression syntax<br \/>\n<code>(obj,args) -&gt; obj.someInstanceMethod(args)<\/code><br \/>\ncan be converted to<br \/>\n<code>objectType::someInstanceMethod<\/code><\/p>\n<p>Let&#8217;s see this with the help of example.<\/p>\n<pre class=\"lang:java mark:11-18,23,28 decode:1 \">\nimport java.util.function.BiFunction;\n\npublic class MethodReferenceObjectType {\n\n    public static void main(String[] args) {\n\n        \/\/ Using anonymous class\n\n        BiFunction&lt;String,Integer,String&gt; bf1=new BiFunction&lt;&gt;() {\n\n            @Override\n            public String apply(String t, Integer u) {\n                return t.substring(u);\n            }\n        };\n        String subString1 = getSubstring(\"Java2blog\",2,bf1);\n        System.out.println(subString1);\n\n        \/\/ Using lambda expression\n        BiFunction&lt;String,Integer,String&gt; bf2 =  (t,u) -&gt; t.substring(u);\n        String subString2 = getSubstring(\"Java2blog\",2,bf2);\n        System.out.println(subString2);\n\n        \/\/ Using Method reference\n        BiFunction&lt;String,Integer,String&gt; bf3 = String::substring;\n        String subString3 = getSubstring(\"Java2blog\",2,bf3);\n        System.out.println(subString3);\n    }\n\n    public static String getSubstring(String str1,int beginIndex,BiFunction&lt;String,Integer,String&gt; p)\n    {\n        return p.apply(str1, beginIndex);\n\n    }\n}\n<\/pre>\n<p><code>BiFunction<\/code> is functional interface that takes two arguments and returns single output.<\/p>\n<p>If you notice,<code>BiFunction&lt;String,Integer,String&gt; bf2 = (t,u) -&gt; t.substring(u);<\/code> is of type <code>(obj,args) -&gt; obj.someInstanceMethod(args)<\/code><\/p>\n<p>Here<\/p>\n<ul>\n<li><code>obj<\/code> is of type String.<\/li>\n<li>someInstanceMethod is String&#8217;s <code>substring()<\/code> method.<\/li>\n<li>args is <code>beginIndex<\/code> for <code>substring()<\/code> method argument.<\/li>\n<\/ul>\n<p>So  <code>BiFunction&lt;String,Integer,String&gt; bf2 =  (t,u) -&gt; t.substring(u);<\/code> can be converted to<br \/>\n<code>  BiFunction&lt;String,Integer,String&gt; bf3 = String::substring;<\/code><\/p>\n<p>Here,<\/p>\n<ul>\n<li>First <code>BiFunction<\/code> parameter type(String) is String object itself.<\/li>\n<li>Second <code>BiFunction<\/code> parameter type(Integer) is argument to <code>substring()<\/code> method<\/li>\n<li>Third <code>BiFunction<\/code> parameter type(String) is return type of <code>substring()<\/code> method<\/li>\n<\/ul>\n<h3><span id=\"23_Reference_to_instance_method_of_existing_object\">2.3 Reference to instance method of existing object<\/span><\/h3>\n<p>When you have lambda expression where instance of object is used to call an instance method with\/without parameters, then you can use method reference to an instance method with an existing object.<br \/>\nLambda expression syntax<br \/>\n<code>(args) -&gt; obj.someInstanceMethod(args)<\/code><br \/>\ncan be converted to<br \/>\n<code>objectType::someInstanceMethod<\/code><\/p>\n<p>Here <code>obj<\/code> is defined somewhere else and is not part of argument to lambda expression.<\/p>\n<p>Let&#8217;s understand with the help of example.<\/p>\n<p>Create a class named <code>Country.java<\/code>.<\/p>\n<pre class=\"lang:java decode:1 \">\npublic class Country {\n    String name;\n    long population;\n\n    Country(String name)\n    {\n        this.name=name;\n    }\n    public String getName() {\n        return name;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n    public long getPopulation() {\n        return population;\n    }\n    public void setPopulation(long population) {\n        this.population = population;\n    }\n\n    @Override\n    public String toString() {\n        return \"[ name = \"+name+\" population = \"+population+\" ]\";\n    }\n}\n<\/pre>\n<p>Create another class <code>MethodReferenceExistingObjectMain.java<\/code><\/p>\n<pre class=\"lang:java mark:12-18,23,28 decode:1 \">\nimport java.util.function.Consumer;\n\npublic class MethodReferenceExistingObjectMain {\n\n    public static void main(String[] args) {\n\n        Country c=new Country(\"India\");\n\n        \/\/ Using anonymous class\n        Consumer&lt;Long&gt; popCons1=new Consumer&lt;Long&gt;() {\n\n            @Override\n            public void accept(Long t) {\n                c.setPopulation(t);\n            }\n        };\n        popCons1.accept(20000L);\n        System.out.println(c);\n\n        \/\/ Using Lambda expression\n        Consumer&lt;Long&gt; popCons2= (population) -&gt; c.setPopulation(population);\n        popCons2.accept(30000L);\n        System.out.println(c);\n\n        \/\/ Using method reference\n        Consumer&lt;Long&gt; popCons3 = c::setPopulation;\n        popCons3.accept(40000L);\n        System.out.println(c);\n    }\n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\n[ name = India population = 20000 ]\n[ name = India population = 30000 ]\n[ name = India population = 40000 ]\n<\/pre>\n<p>Consumer is functional interface which takes single argument and returns nothing.<br \/>\nIf you notice,  <code>Consumer<Long> popCons2 =  (population) -&gt; c.setPopulation(population);<\/code> is of type <code>(args) -&gt; obj.someInstanceMethod(args)<\/code><\/p>\n<p>Here<\/p>\n<ul>\n<li>obj is of type Country and declared somewhere else.<\/li>\n<li>someInstanceMethod is Country&#8217;s setPopulation method.<\/li>\n<li>args is <code>population<\/code> for setPopulation method argument.<\/li>\n<\/ul>\n<p>So  <code>Consumer&lt;Long&gt; popCons2= (population) -&gt; c.setPopulation(population);<\/code> can be converted to <code>Consumer&lt;Long&gt; popCons3 = c::setPopulation;<\/code><\/p>\n<p>Here,<\/p>\n<ul>\n<li>First Consumer parameter type(Long) is argument to setPopulation method.<\/li>\n<\/ul>\n<h3><span id=\"24_Reference_constructor\">2.4 Reference constructor<\/span><\/h3>\n<p>When lambda expression is used to create new object with\/without parameters, then you can use reference method constructor.<br \/>\nLambda expression syntax<br \/>\n<code>(args) -&gt; new ClassName(args)<\/code><br \/>\ncan be converted to<br \/>\n<code>ClassName::new<\/code><\/p>\n<p>Let&#8217;s see with the help of example.<br \/>\nHere we will convert the list to set using method reference.<\/p>\n<p><code>Function&lt;List<String>,Set<String>&gt;<\/code> is functional interface which will take a list an argument and will return set by calling HashSet <a href=\"https:\/\/java2blog.com\/constructor-java\/\" rel=\"noopener noreferrer\" target=\"_blank\">constructor<\/a> <code>public HashSet(Collection&lt;? extends E&gt; c)<\/code><\/p>\n<pre class=\"lang:java decode:1 \">\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.function.Function;\n\npublic class MethodReferenceConstructorMain {\n\n    public static void main(String[] args) {\n\n        ArrayList&lt;String&gt; list=new ArrayList&lt;&gt;();\n        list.add(\"Rohan\");\n        list.add(\"Andy\");\n        list.add(\"Sneha\");\n        list.add(\"Rohan\");\n\n        \/\/ Anonymous class\n        Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f1= new Function&lt;List&lt;String&gt;, Set&lt;String&gt;&gt;() {\n\n            @Override\n            public Set&lt;String&gt; apply(List&lt;String&gt; nameList) {\n\n                return new HashSet&lt;&gt;(nameList);\n            }\n        };\n        Set&lt;String&gt; set1 = f1.apply(list);\n        System.out.println(set1);\n\n        \/\/ Using lambda expression\n        Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f2 = (nameList) -&gt; new HashSet&lt;&gt;(nameList);\n        Set&lt;String&gt; set2 = f2.apply(list);\n        System.out.println(set2);\n\n        \/\/ Using Method reference\n        Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f3= HashSet::new;\n        Set&lt;String&gt; set = f3.apply(list);\n        System.out.println(set);\n    }\n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\n[Sneha, Andy, Rohan]\n[Sneha, Andy, Rohan]\n[Sneha, Andy, Rohan]\n<\/pre>\n<p>If you notice,  <code>Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f2 = (nameList) -&gt; new HashSet&lt;&gt;(nameList);<\/code> is of type <code>(args) -&gt; new ClassName(args)<\/code><\/p>\n<p>Here<\/p>\n<ul>\n<li>args is of type <code>list<\/code> <\/li>\n<li>ClassName is <code>HashSet<\/code><\/li>\n<\/ul>\n<p>So  <code>Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f2 = (nameList) -&gt; new HashSet&lt;&gt;(nameList);<\/code> can be converted to <code>Function&lt;List&lt;String&gt;,Set&lt;String&gt;&gt; f3= HashSet::new;<\/code><\/p>\n<p>Here,<\/p>\n<ul>\n<li>First <code>Function<\/code> parameter type(List) is argument to HashSet constructor.<\/li>\n<\/ul>\n<h2><span id=\"3_Excercise\">3. Excercise<\/span><\/h2>\n<p>Let&#8217;s practice few exercises based on Method reference.<\/p>\n<div class=\"content-box-grey\">\n<h3><span id=\"31_Excercise1\">3.1 Excercise:1<\/span><\/h3>\n<p>Given a list of Integer, you need to find square root of each number in the list and return it as List&lt;Double&gt;.<br \/>\nYou need to call Math&#8217;s <code>sqrt<\/code> static method to find square root of number and use it as <code>method reference<\/code>.<\/p>\n<div id=\"toc_container\"><div id=\"question1-link-9355\" class=\"sh-link question1-link sh-hide\"><a href=\"#\" onclick=\"showhide_toggle('question1', 9355, 'Show Answer', 'Hide Answers'); return false;\" aria-expanded=\"false\"><span id=\"question1-toggle-9355\">Show Answer<\/span><\/a><\/div><div id=\"question1-content-9355\" class=\"sh-content question1-content sh-hide\" style=\"display: none;\">\nWe can create <a href=\"https:\/\/java2blog.com\/java-8-function-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">Function<\/a> functional interface with method reference and pass it to Stream&#8217;s map method.<\/p>\n<pre class=\"lang:java mark:15,20 decode:1 \" >\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\nimport java.util.function.Function;\r\nimport java.util.stream.Collectors;\r\n\r\npublic class MethodReferenceSqrt {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tList&lt;Integer&gt; list=Arrays.asList(new Integer[] {25,43,52,31,81});\r\n\t\t\r\n\t\t\/\/ Using lambda expression\r\n\t\tFunction&lt;Integer,Double&gt; function1= (num) -&gt; Math.sqrt(num);\r\n\t\tList&lt;Double&gt; collect1 = list.stream().map(function1).collect(Collectors.toList());\r\n\t\tSystem.out.println(collect1);\r\n\t\t\r\n\t\t\/\/ Using method reference\r\n\t\tFunction&lt;Integer,Double&gt; function2= Math::sqrt;\r\n\t\tList&lt;Double&gt; collect2 = list.stream().map(function2).collect(Collectors.toList());\r\n\t\tSystem.out.println(collect2);\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\r\n[5.0, 6.557438524302, 7.211102550927978, 5.5677643628300215, 9.0]\r\n[5.0, 6.557438524302, 7.211102550927978, 5.5677643628300215, 9.0]\r\n\r\n<\/pre>\n<\/div>\n<\/div><\/div>\n<div class=\"content-box-grey\">\n<h3><span id=\"32_Excercise2\">3.2 Excercise:2<\/span><\/h3>\n<p>Given a [list of Strings](https:\/\/java2blog.com\/list-string-java\/ &#8220;list of Strings&#8221;), you need to convert all the String to <code>uppercase<\/code> and then return a new <code>list<\/code>.<\/p>\n<div id=\"toc_container\"><div id=\"question2-link-9355\" class=\"sh-link question2-link sh-hide\"><a href=\"#\" onclick=\"showhide_toggle('question2', 9355, 'Show Answer', 'Hide Answers'); return false;\" aria-expanded=\"false\"><span id=\"question2-toggle-9355\">Show Answer<\/span><\/a><\/div><div id=\"question2-content-9355\" class=\"sh-content question2-content sh-hide\" style=\"display: none;\">\nWe can create <a href=\"https:\/\/java2blog.com\/java-8-function-example\/\" rel=\"noopener noreferrer\" target=\"_blank\">Function<String,String><\/a> functional interface with method reference and pass it to Stream&#8217;s map method.<\/p>\n<pre class=\"lang:java mark:17,23 decode:1 \" >\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\nimport java.util.function.Function;\r\nimport java.util.stream.Collectors;\r\n\r\npublic class MethodReferenceUpperCase {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tList&lt;String&gt; listOfNames = Arrays.asList(new String[] \r\n                {\"Andrew\",\"Mary\",\"Sohan\",\"Deby\"});\r\n\t\t\r\n\t\t\/\/ Using lambda expression\r\n\t\tFunction&lt;String,String&gt; function1= (name) -&gt; name.toUpperCase();\r\n\t\tArrayList&lt;String&gt; collect1 = listOfNames.stream().map(function1)\r\n\t        .collect(Collectors.toCollection(ArrayList::new));\r\n\t\tSystem.out.println(collect1);\r\n\t\t\r\n\t\t\/\/ Using method reference\r\n\t\tFunction&lt;String,String&gt; function2= String::toUpperCase;\r\n\t\tArrayList&lt;String&gt; collect2 = listOfNames.stream().map(function2)  \t\t\t\t\t\t                                \r\n                .collect(Collectors.toCollection(ArrayList::new));\r\n\t\tSystem.out.println(collect2);\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\r\n[ANDREW, MARY, SOHAN, DEBY]\r\n[ANDREW, MARY, SOHAN, DEBY]\r\n<\/pre>\n<p>If you notice, we are calling String&#8217;s <code>toUpperCase()<\/code> in lambda expression, hence<br \/>\nwe can convert <code>Function&lt;String,String&gt; function1= (name) -&gt; name.toUpperCase();<\/code><br \/>\nto<br \/>\n<code>Function&lt;String,String&gt; function2= String::toUpperCase;<\/code>.<br \/>\n<\/div><\/div>\n<\/div>\n<div class=\"content-box-grey\">\n<h3><span id=\"33_Excercise3\">3.3 Excercise:3<\/span><\/h3>\n<p>Given a list of Color objects, you need to sort them of color&#8217;s name and return a sorted list of color names(<code>List<string><\/string><\/code>)<br \/>\nHere is the definition of Color class.<\/p>\n<pre class=\"lang:java decode:1 \">\npublic class Color {\n\n    String name;\n    String htmlCode;\n\n    public Color(String name, String htmlCode) {\n        super();\n        this.name = name;\n        this.htmlCode = htmlCode;\n    }\n\n    public String getName() {\n        return name;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n    public String getHtmlCode() {\n        return htmlCode;\n    }\n    public void setHtmlCode(String htmlCode) {\n        this.htmlCode = htmlCode;\n    }\n\n    @Override\n    public String toString() {\n        return \"Color [name:\"+name+\" HtmlCode:\"+htmlCode+\"]\";\n    }\n\n}\n\n<\/pre>\n<div id=\"toc_container\"><div id=\"question3-link-9355\" class=\"sh-link question3-link sh-hide\"><a href=\"#\" onclick=\"showhide_toggle('question3', 9355, 'Show Answer', 'Hide Answers'); return false;\" aria-expanded=\"false\"><span id=\"question3-toggle-9355\">Show Answer<\/span><\/a><\/div><div id=\"question3-content-9355\" class=\"sh-content question3-content sh-hide\" style=\"display: none;\">\nWe can use method reference in <a href=\"https:\/\/java2blog.com\/java-8-stream-map\/\" rel=\"noopener noreferrer\" target=\"_blank\">map<\/a> and sorted method as below.<\/p>\n<pre class=\"lang:java mark:31-32 decode:1 \" >\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.stream.Collectors;\r\n\r\npublic class SortByColorCodeMain {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\t\/\/ Sort list of colors by name\r\n\r\n\t\tList&lt;Color&gt; listOfColors = getListOfColors();\r\n\t\tSystem.out.println(\"==========================\");\r\n\t\tSystem.out.println(\"Using Lambda expressions\");\r\n\t\tSystem.out.println(\"==========================\");\r\n\t\t\r\n\t\t\/\/ Using lambda expressions\r\n\t\tList&lt;String&gt; sortedListOfColorNames = listOfColors.stream()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  .map(c -&gt; c.getName())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  .sorted((c1, c2) -&gt; c1.compareTo(c2))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  .collect(Collectors.toList());\r\n\t\t\r\n\t\tsortedListOfColorNames.forEach(System.out::println);\r\n\t\tSystem.out.println(\"==========================\");\r\n\t\tSystem.out.println(\"Using Method reference\");\r\n\t\tSystem.out.println(\"==========================\");\r\n\t\t\r\n\t\t\/\/ Using MethodReference\r\n\t\tList&lt;String&gt; sortedListOfColorNamesMR = listOfColors.stream()\r\n\t\t\t\t                                      .map(Color::getName)\r\n\t\t\t\t                                      .sorted(String::compareTo)\r\n\t\t\t\t                                      .collect(Collectors.toList());\r\n\t\tsortedListOfColorNamesMR.forEach(System.out::println);\r\n\r\n\t}\r\n\r\n\tpublic static List&lt;Color&gt; getListOfColors() {\r\n\t\tList&lt;Color&gt; listOfColors = new ArrayList&lt;&gt;();\r\n\r\n\t\tColor red = new Color(\"Red\", \"#FF0000\");\r\n\t\tColor blue = new Color(\"Blue\", \"0000FF\");\r\n\t\tColor white = new Color(\"White\", \"#FFFFFF\");\r\n\t\tColor green = new Color(\"Green\", \"#008000\");\r\n\r\n\t\tlistOfColors.add(red);\r\n\t\tlistOfColors.add(blue);\r\n\t\tlistOfColors.add(white);\r\n\t\tlistOfColors.add(green);\r\n\r\n\t\treturn listOfColors;\r\n\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre title=\"Output\">\r\n==========================\r\nUsing Lambda expressions\r\n==========================\r\nBlue\r\nGreen\r\nRed\r\nWhite\r\n==========================\r\nUsing Method reference\r\n==========================\r\nBlue\r\nGreen\r\nRed\r\nWhite\r\n\r\n<\/pre>\n<\/div><\/div>\n<\/div>\n<h2><span id=\"4_Conclusion\">4. Conclusion<\/span><\/h2>\n<p>Method references are special type of lambda expression that simply calls a method. It makes code more readable and concise, but if method references lead to any confusion, then there is no point in using them.<\/p>\n<p>That&#8217;s all about method references in java.<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Table of Contents1. Introduction to Method Reference2. Types of method references2.1 Reference to static method2.2 Reference to instance method of object type2.3 Reference to instance method of existing object2.4 Reference constructor3. Excercise3.1 Excercise:13.2 Excercise:23.3 Excercise:34. Conclusion Java 8 has introduced a lot of new features such as lambda expressions, stream, Method references etc. In this [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12589,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[36],"tags":[222],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/9355"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=9355"}],"version-history":[{"count":2,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/9355\/revisions"}],"predecessor-version":[{"id":26039,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/9355\/revisions\/26039"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12589"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=9355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=9355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=9355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}