How to iterate over lambda functions in Java

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
12
down vote

favorite
1












I was able to do it in Python and my Python code is:



signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b

a = 5
b = 3
for i in signs.keys():
print(signs[i](a,b))


And the output is:



8
2


How do I do this same thing in Java through HashMap?







share|improve this question






















  • Java is only a very tiny bit more verbose
    – Walter Tross
    Aug 25 at 9:08










  • except that in python AFAIK lambdas are limited to a single statement, right?
    – Eugene
    Aug 25 at 12:00






  • 2




    @Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
    – wizzwizz4
    Aug 25 at 15:28











  • @WalterTross Oops. Values are literals, aren't they? :-/
    – wizzwizz4
    Aug 25 at 15:31










  • Literals are values, but not vice versa.
    – Midnightas
    Aug 25 at 18:41














up vote
12
down vote

favorite
1












I was able to do it in Python and my Python code is:



signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b

a = 5
b = 3
for i in signs.keys():
print(signs[i](a,b))


And the output is:



8
2


How do I do this same thing in Java through HashMap?







share|improve this question






















  • Java is only a very tiny bit more verbose
    – Walter Tross
    Aug 25 at 9:08










  • except that in python AFAIK lambdas are limited to a single statement, right?
    – Eugene
    Aug 25 at 12:00






  • 2




    @Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
    – wizzwizz4
    Aug 25 at 15:28











  • @WalterTross Oops. Values are literals, aren't they? :-/
    – wizzwizz4
    Aug 25 at 15:31










  • Literals are values, but not vice versa.
    – Midnightas
    Aug 25 at 18:41












up vote
12
down vote

favorite
1









up vote
12
down vote

favorite
1






1





I was able to do it in Python and my Python code is:



signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b

a = 5
b = 3
for i in signs.keys():
print(signs[i](a,b))


And the output is:



8
2


How do I do this same thing in Java through HashMap?







share|improve this question














I was able to do it in Python and my Python code is:



signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b

a = 5
b = 3
for i in signs.keys():
print(signs[i](a,b))


And the output is:



8
2


How do I do this same thing in Java through HashMap?









share|improve this question













share|improve this question




share|improve this question








edited Aug 25 at 20:36









Peter Mortensen

12.9k1983111




12.9k1983111










asked Aug 25 at 8:39









Shivansh Kuchhal

746




746











  • Java is only a very tiny bit more verbose
    – Walter Tross
    Aug 25 at 9:08










  • except that in python AFAIK lambdas are limited to a single statement, right?
    – Eugene
    Aug 25 at 12:00






  • 2




    @Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
    – wizzwizz4
    Aug 25 at 15:28











  • @WalterTross Oops. Values are literals, aren't they? :-/
    – wizzwizz4
    Aug 25 at 15:31










  • Literals are values, but not vice versa.
    – Midnightas
    Aug 25 at 18:41
















  • Java is only a very tiny bit more verbose
    – Walter Tross
    Aug 25 at 9:08










  • except that in python AFAIK lambdas are limited to a single statement, right?
    – Eugene
    Aug 25 at 12:00






  • 2




    @Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
    – wizzwizz4
    Aug 25 at 15:28











  • @WalterTross Oops. Values are literals, aren't they? :-/
    – wizzwizz4
    Aug 25 at 15:31










  • Literals are values, but not vice versa.
    – Midnightas
    Aug 25 at 18:41















Java is only a very tiny bit more verbose
– Walter Tross
Aug 25 at 9:08




Java is only a very tiny bit more verbose
– Walter Tross
Aug 25 at 9:08












except that in python AFAIK lambdas are limited to a single statement, right?
– Eugene
Aug 25 at 12:00




except that in python AFAIK lambdas are limited to a single statement, right?
– Eugene
Aug 25 at 12:00




2




2




@Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
– wizzwizz4
Aug 25 at 15:28





@Eugene Actually, in Python lambdas are limited to no statements at all. Only expressions are allowed.
– wizzwizz4
Aug 25 at 15:28













@WalterTross Oops. Values are literals, aren't they? :-/
– wizzwizz4
Aug 25 at 15:31




@WalterTross Oops. Values are literals, aren't they? :-/
– wizzwizz4
Aug 25 at 15:31












Literals are values, but not vice versa.
– Midnightas
Aug 25 at 18:41




Literals are values, but not vice versa.
– Midnightas
Aug 25 at 18:41












2 Answers
2






active

oldest

votes

















up vote
21
down vote



accepted










You can use BinaryOperator<Integer> in this case like so :



BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

// Then create a new Map which take the sign and the corresponding BinaryOperator
// equivalent to signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

int a = 5; // a = 5
int b = 3; // b = 3

// Loop over the sings map and apply the operation
signs.values().forEach(v -> System.out.println(v.apply(a, b)));


Outputs



8
2



Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so:



Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
signs.put("+", add);
signs.put("-", sub);


Ideone demo




Good practice



As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this :



// signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
int a = 5; // a = 5
int b = 3; // b = 3
// for i in signs.keys(): print(signs[i](a,b))
signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));





share|improve this answer


















  • 3




    IntBinaryOperator is probably a better choice...
    – Boris the Spider
    Aug 25 at 8:47







  • 2




    Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
    – YCF_L
    Aug 25 at 8:55






  • 3




    It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
    – Boris the Spider
    Aug 25 at 8:56







  • 1




    If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
    – Federico Peralta Schaffner
    Aug 25 at 22:31






  • 2




    Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
    – Holger
    Aug 27 at 8:30


















up vote
14
down vote













Create yourself a nice, typesafe, enum:



enum Operator implements IntBinaryOperator 
PLUS("+", Integer::sum),
MINUS("-", (a, b) -> a - b);

private final String symbol;
private final IntBinaryOperator op;

Operator(final String symbol, final IntBinaryOperator op)
this.symbol = symbol;
this.op = op;


public String symbol()
return symbol;


@Override
public int applyAsInt(final int left, final int right)
return op.applyAsInt(left, right);




You may want a lambda that returns double rather than int for other operators.



Now, simply dump that into a Map:



final var operators = Arrays.stream(Operator.values())
.collect(toMap(Operator::symbol, identity()));


For your example though, you don't need a Map at all:



Arrays.stream(Operator.values())
.mapToInt(op -> op.applyAsInt(a,b))
.forEach(System.out::println);



Using:



import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;





share|improve this answer






















    Your Answer





    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52015479%2fhow-to-iterate-over-lambda-functions-in-java%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    21
    down vote



    accepted










    You can use BinaryOperator<Integer> in this case like so :



    BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
    BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

    // Then create a new Map which take the sign and the corresponding BinaryOperator
    // equivalent to signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

    int a = 5; // a = 5
    int b = 3; // b = 3

    // Loop over the sings map and apply the operation
    signs.values().forEach(v -> System.out.println(v.apply(a, b)));


    Outputs



    8
    2



    Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so:



    Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
    signs.put("+", add);
    signs.put("-", sub);


    Ideone demo




    Good practice



    As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this :



    // signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
    int a = 5; // a = 5
    int b = 3; // b = 3
    // for i in signs.keys(): print(signs[i](a,b))
    signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));





    share|improve this answer


















    • 3




      IntBinaryOperator is probably a better choice...
      – Boris the Spider
      Aug 25 at 8:47







    • 2




      Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
      – YCF_L
      Aug 25 at 8:55






    • 3




      It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
      – Boris the Spider
      Aug 25 at 8:56







    • 1




      If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
      – Federico Peralta Schaffner
      Aug 25 at 22:31






    • 2




      Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
      – Holger
      Aug 27 at 8:30















    up vote
    21
    down vote



    accepted










    You can use BinaryOperator<Integer> in this case like so :



    BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
    BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

    // Then create a new Map which take the sign and the corresponding BinaryOperator
    // equivalent to signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

    int a = 5; // a = 5
    int b = 3; // b = 3

    // Loop over the sings map and apply the operation
    signs.values().forEach(v -> System.out.println(v.apply(a, b)));


    Outputs



    8
    2



    Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so:



    Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
    signs.put("+", add);
    signs.put("-", sub);


    Ideone demo




    Good practice



    As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this :



    // signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
    int a = 5; // a = 5
    int b = 3; // b = 3
    // for i in signs.keys(): print(signs[i](a,b))
    signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));





    share|improve this answer


















    • 3




      IntBinaryOperator is probably a better choice...
      – Boris the Spider
      Aug 25 at 8:47







    • 2




      Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
      – YCF_L
      Aug 25 at 8:55






    • 3




      It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
      – Boris the Spider
      Aug 25 at 8:56







    • 1




      If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
      – Federico Peralta Schaffner
      Aug 25 at 22:31






    • 2




      Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
      – Holger
      Aug 27 at 8:30













    up vote
    21
    down vote



    accepted







    up vote
    21
    down vote



    accepted






    You can use BinaryOperator<Integer> in this case like so :



    BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
    BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

    // Then create a new Map which take the sign and the corresponding BinaryOperator
    // equivalent to signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

    int a = 5; // a = 5
    int b = 3; // b = 3

    // Loop over the sings map and apply the operation
    signs.values().forEach(v -> System.out.println(v.apply(a, b)));


    Outputs



    8
    2



    Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so:



    Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
    signs.put("+", add);
    signs.put("-", sub);


    Ideone demo




    Good practice



    As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this :



    // signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
    int a = 5; // a = 5
    int b = 3; // b = 3
    // for i in signs.keys(): print(signs[i](a,b))
    signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));





    share|improve this answer














    You can use BinaryOperator<Integer> in this case like so :



    BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
    BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

    // Then create a new Map which take the sign and the corresponding BinaryOperator
    // equivalent to signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

    int a = 5; // a = 5
    int b = 3; // b = 3

    // Loop over the sings map and apply the operation
    signs.values().forEach(v -> System.out.println(v.apply(a, b)));


    Outputs



    8
    2



    Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so:



    Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
    signs.put("+", add);
    signs.put("-", sub);


    Ideone demo




    Good practice



    As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this :



    // signs = "+" : lambda a, b : a + b, "-" : lambda a, b : a - b
    Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
    int a = 5; // a = 5
    int b = 3; // b = 3
    // for i in signs.keys(): print(signs[i](a,b))
    signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 27 at 8:48

























    answered Aug 25 at 8:45









    YCF_L

    31.5k103273




    31.5k103273







    • 3




      IntBinaryOperator is probably a better choice...
      – Boris the Spider
      Aug 25 at 8:47







    • 2




      Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
      – YCF_L
      Aug 25 at 8:55






    • 3




      It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
      – Boris the Spider
      Aug 25 at 8:56







    • 1




      If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
      – Federico Peralta Schaffner
      Aug 25 at 22:31






    • 2




      Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
      – Holger
      Aug 27 at 8:30













    • 3




      IntBinaryOperator is probably a better choice...
      – Boris the Spider
      Aug 25 at 8:47







    • 2




      Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
      – YCF_L
      Aug 25 at 8:55






    • 3




      It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
      – Boris the Spider
      Aug 25 at 8:56







    • 1




      If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
      – Federico Peralta Schaffner
      Aug 25 at 22:31






    • 2




      Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
      – Holger
      Aug 27 at 8:30








    3




    3




    IntBinaryOperator is probably a better choice...
    – Boris the Spider
    Aug 25 at 8:47





    IntBinaryOperator is probably a better choice...
    – Boris the Spider
    Aug 25 at 8:47





    2




    2




    Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
    – YCF_L
    Aug 25 at 8:55




    Thank you @BoristheSpider I don't work with IntBinaryOperator before, I will learn about this, I see your answer and find that you already using it +1
    – YCF_L
    Aug 25 at 8:55




    3




    3




    It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
    – Boris the Spider
    Aug 25 at 8:56





    It's (int, int) -> int rather than Integer - so less boxing. Your answer is good though - +1!
    – Boris the Spider
    Aug 25 at 8:56





    1




    1




    If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
    – Federico Peralta Schaffner
    Aug 25 at 22:31




    If you're using java 10, it's OK to define the map as var signs = Map.of("+", add, "-", sub);
    – Federico Peralta Schaffner
    Aug 25 at 22:31




    2




    2




    Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
    – Holger
    Aug 27 at 8:30





    Even with boxed values, you can use BinaryOperator<Integer> here, which is a subtype of BiFunction<Integer, Integer, Integer>. Further, you don’t need to verbosely declare local variables for the functions: Map<String, BinaryOperator<Integer>> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);; this is much closer to the OP’s Python code. Of course, whenever the use case allows to use IntBinaryOperator instead, it’s preferable, as it avoids boxing overhead (and is even shorter than BinaryOperator<Integer>)…
    – Holger
    Aug 27 at 8:30













    up vote
    14
    down vote













    Create yourself a nice, typesafe, enum:



    enum Operator implements IntBinaryOperator 
    PLUS("+", Integer::sum),
    MINUS("-", (a, b) -> a - b);

    private final String symbol;
    private final IntBinaryOperator op;

    Operator(final String symbol, final IntBinaryOperator op)
    this.symbol = symbol;
    this.op = op;


    public String symbol()
    return symbol;


    @Override
    public int applyAsInt(final int left, final int right)
    return op.applyAsInt(left, right);




    You may want a lambda that returns double rather than int for other operators.



    Now, simply dump that into a Map:



    final var operators = Arrays.stream(Operator.values())
    .collect(toMap(Operator::symbol, identity()));


    For your example though, you don't need a Map at all:



    Arrays.stream(Operator.values())
    .mapToInt(op -> op.applyAsInt(a,b))
    .forEach(System.out::println);



    Using:



    import static java.util.function.Function.identity;
    import static java.util.stream.Collectors.toMap;





    share|improve this answer


























      up vote
      14
      down vote













      Create yourself a nice, typesafe, enum:



      enum Operator implements IntBinaryOperator 
      PLUS("+", Integer::sum),
      MINUS("-", (a, b) -> a - b);

      private final String symbol;
      private final IntBinaryOperator op;

      Operator(final String symbol, final IntBinaryOperator op)
      this.symbol = symbol;
      this.op = op;


      public String symbol()
      return symbol;


      @Override
      public int applyAsInt(final int left, final int right)
      return op.applyAsInt(left, right);




      You may want a lambda that returns double rather than int for other operators.



      Now, simply dump that into a Map:



      final var operators = Arrays.stream(Operator.values())
      .collect(toMap(Operator::symbol, identity()));


      For your example though, you don't need a Map at all:



      Arrays.stream(Operator.values())
      .mapToInt(op -> op.applyAsInt(a,b))
      .forEach(System.out::println);



      Using:



      import static java.util.function.Function.identity;
      import static java.util.stream.Collectors.toMap;





      share|improve this answer
























        up vote
        14
        down vote










        up vote
        14
        down vote









        Create yourself a nice, typesafe, enum:



        enum Operator implements IntBinaryOperator 
        PLUS("+", Integer::sum),
        MINUS("-", (a, b) -> a - b);

        private final String symbol;
        private final IntBinaryOperator op;

        Operator(final String symbol, final IntBinaryOperator op)
        this.symbol = symbol;
        this.op = op;


        public String symbol()
        return symbol;


        @Override
        public int applyAsInt(final int left, final int right)
        return op.applyAsInt(left, right);




        You may want a lambda that returns double rather than int for other operators.



        Now, simply dump that into a Map:



        final var operators = Arrays.stream(Operator.values())
        .collect(toMap(Operator::symbol, identity()));


        For your example though, you don't need a Map at all:



        Arrays.stream(Operator.values())
        .mapToInt(op -> op.applyAsInt(a,b))
        .forEach(System.out::println);



        Using:



        import static java.util.function.Function.identity;
        import static java.util.stream.Collectors.toMap;





        share|improve this answer














        Create yourself a nice, typesafe, enum:



        enum Operator implements IntBinaryOperator 
        PLUS("+", Integer::sum),
        MINUS("-", (a, b) -> a - b);

        private final String symbol;
        private final IntBinaryOperator op;

        Operator(final String symbol, final IntBinaryOperator op)
        this.symbol = symbol;
        this.op = op;


        public String symbol()
        return symbol;


        @Override
        public int applyAsInt(final int left, final int right)
        return op.applyAsInt(left, right);




        You may want a lambda that returns double rather than int for other operators.



        Now, simply dump that into a Map:



        final var operators = Arrays.stream(Operator.values())
        .collect(toMap(Operator::symbol, identity()));


        For your example though, you don't need a Map at all:



        Arrays.stream(Operator.values())
        .mapToInt(op -> op.applyAsInt(a,b))
        .forEach(System.out::println);



        Using:



        import static java.util.function.Function.identity;
        import static java.util.stream.Collectors.toMap;






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 25 at 8:54

























        answered Aug 25 at 8:45









        Boris the Spider

        43.1k370117




        43.1k370117



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52015479%2fhow-to-iterate-over-lambda-functions-in-java%23new-answer', 'question_page');

            );

            Post as a guest













































































            Comments

            Popular posts from this blog

            What does second last employer means? [closed]

            List of Gilmore Girls characters

            One-line joke