Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava EnumsJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava Exceptions

Java File Handling

Java FilesJava Create/Write FilesJava Read FilesJava Delete Files

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava Iterator

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java How To's

Add Two NumbersCount WordsReverse a StringSum of Array ElementsConvert String to ArraySort an ArrayFind Array AverageFind Smallest ElementArrayList LoopHashMap LoopLoop Through an EnumArea of RectangleEven or Odd NumberPositive or NegativeSquare RootRandom Number

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava Iterator MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava CompilerJava ExercisesJava QuizJava ServerJava SyllabusJava Study PlanJava Certificate


JavaLambda Expressions


Java Lambda Expressions

Lambda Expressions were added in Java 8.

A lambda expression is a short block of code which takes in parameters and returns avalue. Lambda expressions are similar to methods, but they do not need a name and theycan be implemented right in the body of a method.


Syntax

The simplest lambda expression contains a single parameter and an expression:

parameter ->expression

To use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) ->expression

Expressions are limited. They have to immediately return a value, and they cannot containvariables, assignments or statements such asif orfor. In order to do more complexoperations, a code block can be used with curly braces. If the lambda expression needs toreturn a value, then the code block should have areturn statement.

(parameter1, parameter2) -> {code block }


Using Lambda Expressions

Lambda expressions are usually passed as parameters to a function:

Example

Use a lambda expression in theArrayList'sforEach() method to printevery item in the list:

import java.util.ArrayList;public class Main {  public static void main(String[] args) {    ArrayList<Integer> numbers = new ArrayList<Integer>();    numbers.add(5);    numbers.add(9);    numbers.add(8);    numbers.add(1);    numbers.forEach( (n) -> { System.out.println(n); } );  }}

Try it Yourself »

Lambda expressions can be stored in variables if the variable's type is an interface whichhas only one method. The lambda expression should have the same number ofparameters and the same return type as that method. Java has many of these kinds ofinterfaces built in, such as theConsumer interface (found in thejava.util package) used by lists.

Example

Use Java'sConsumer interface to store a lambda expression in a variable:

import java.util.ArrayList;import java.util.function.Consumer;public class Main {  public static void main(String[] args) {    ArrayList<Integer> numbers = new ArrayList<Integer>();    numbers.add(5);    numbers.add(9);    numbers.add(8);    numbers.add(1);    Consumer<Integer> method = (n) -> { System.out.println(n); };    numbers.forEach( method );  }}

Try it Yourself »

To use a lambda expression in a method, the method should have a parameter with asingle-method interface as its type. Calling the interface's method will run the lambdaexpression:

Example

Create a method which takes a lambda expression as a parameter:

interface StringFunction {  String run(String str);}public class Main {  public static void main(String[] args) {    StringFunction exclaim = (s) -> s + "!";    StringFunction ask = (s) -> s + "?";    printFormatted("Hello", exclaim);    printFormatted("Hello", ask);}  public static void printFormatted(String str, StringFunction format) {    String result = format.run(str);    System.out.println(result);}}

Try it Yourself »




 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp