Tutorial Let's use streams and lambdas!

Discussion in 'Resources' started by Plugers11, Jun 27, 2017.

?

Useful?

  1. Yeah, tell me more :D

    4 vote(s)
    66.7%
  2. Wat is dat

    0 vote(s)
    0.0%
  3. Hey i know you!

    0 vote(s)
    0.0%
  4. Thanks for coming back :D

    1 vote(s)
    16.7%
  5. can anyone buy me a kebab?

    1 vote(s)
    16.7%
Thread Status:
Not open for further replies.
  1. Offline

    Plugers11

    JAVA 8 REQUIREMENT

    Hey! I'm back after nearly 2 years, and there is tutorial :D Hope you enjoy! HF
    My english skills are not very powerful but i will try to tell you as best as i could :)
    Let's start

    Lesson 1 - introduce (open)

    Let's start with lambdas
    Lambda -
    So how it works?
    Basically the lambda expression took >= 0 arguments to do stuff. It's kinda higher level of abstraction.

    Stop talking let's start!
    Let's use interfaces. For example: you have to create anonymous class, well first thing which came to your mind would be:
    Code:
    CustomInterface greeting = new CustomInterface() {
                public void greetSomeone(String name) {
                    System.out.println("Hey " + name);
                }
            };
    Let's do this with lambda expression.
    Code:
    CustomClass greet = (String name) -> System.out.println("Hey" + name);
    As you can see lambda take a parameter |name| and then it prints it. Easy, isn't it?

    Another example of lambda
    Let's say you want to create a new Thread. Let's name it: lambdaThread

    There are 3 ways:
    1) Create custom class and extend it from Thread / BukkitRunnable or anything u want and then create new instance of it and run it
    2) Create anonymous class inside function for example
    3) Use lambdas

    Let's go into 3rd option
    Name of our variable is lambdaThread.
    Code:
    Runnable lambdaThread = (/*No arguments there [look for run() method]*/) -> {
    //Do stuff here like in run() method
    }
    new Thread(lambdaThread).start();
    Isn't that easier for small things, rather than coding things like 1,2 options?
    Ofc it is :D

    So when to use it?

    Everyone has his own ideas and so, but for me for what purpose i'm using lambdas is:
    - interfaces
    - when you have to deal with short code
    - forEach method - which i'm gonna explain in next paragraph

    As i said everyone has their own feeling when to use it, but try to not overcomplicating it!

    Introduction to streams
    Stream ->
    Let's start with something easy
    Let's say we have an array of strings
    Code:
    List<String> stringArray = new ArrayList<>();
    Now i will show you the ,,old" method to print all the values from the list
    Code:
    for(String s : stringArray){
    System.out.println(s);
    }

    Now let's use streams and lambda!
    Code:
    stringArray.stream().forEach((String s) -> System.out.println(s));
    And that's it!


    Lesson 2 - Sorting and getting highest score (open)

    What we will cover today?
    Let's make a simple class, named Person
    variables:
    name
    score

    What we want to do is create a new List of Players and get highest score.
    Let's use lambdas!

    Code:
    List<Person> pL = new ArrayList<();[/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR][/COLOR]
    [COLOR=#00ff00][COLOR=rgb(0, 0, 0)][COLOR=#00ff00][COLOR=rgb(0, 0, 0)][COLOR=#00ff00][COLOR=rgb(0, 0, 0)][COLOR=#00ff00][COLOR=rgb(0, 0, 0)][COLOR=#00ff00][COLOR=rgb(0, 0, 0)][COLOR=#00ff00][COLOR=rgb(0, 0, 0)]
    //Add some persons here
            List<Person> pL = new ArrayList<>();
            pL.add(new Person("test1", 50));
            pL.add(new Person("test2", 100));
            pL.add(new Person("test3", 10));
    
            pL = pL.stream().sorted((p1, p2) -> Integer.compare(p1.getScore(), p2.getScore())).collect(Collectors.toList());
    
            List<Integer> scores = pL.stream().map(p -> p.getScore()).collect(Collectors.toList());
            int bestScore = scores.get(scores.size() - 1);
    
            Person theBest = scoresPpl.get(scoresPpl.size() - 1);
    
            System.out.println(theBest.getName() + ":" + theBest.getScore() + "\n");
            System.out.println(bestScore);
    


    Now, what the hell happened?
    So as first we created a new List of Persons and added 3 of them
    Then i used a stream method, and wanted to sort these values, by scores, using lambda we use p1,p2 which are Person variables [you don't have to type classes, cuz Java already knows what's the type of class it is], and comparing their scores.

    But wtf is Integer.compare method?
    Well it's comparing two integers and returns a value : -1, 0 or 1
    -1 = p1 < p2
    0 = p1 = p2
    1 = p1 > p2

    What's #collect?
    Then we use .collect(Collectors.toList()); which parse our method to a List

    What's next?
    We can iterate through the list and get the top player!
    The sorting will sort from lowest to highest score, so the last score will be the highest!

    But what about if we want to get only scores as a list?
    Then we can do something like this:
    List<Integer> scores....
    We start from typing our pL list and using stream and then... we use map function
    What is this doing?
    Basically it's telling to list from lambda what type of data should it have, so there we have p.getScore() so it's saying that only scores will be inside our list. Great isn't it?

    And then ofc printing and checking if that works!

    Thanks for reading! That lesson was little harder, but when you try it, it's awesome and easy!



    Hope you enjoyed the thread, i'm looking forward to hear the opinions ;)
    I will write stuff about Predicate, and some more functions from streams cuz there are a lot of them :D. Peace
     
    Last edited: Jul 2, 2017
  2. Offline

    pretocki3

    @Plugers11 Actually you can use Method Reference instead of slow lamda.
    Simply use this code.
    Code:
    stringArray.stream().forEach(System.out::println)
    Also, you don't need to write stream() for forEach.
    Code:
    stringArray.forEach(System.out::println)
    + You should write JAVA 8 Requirement.
     
    Plugers11 likes this.
  3. Offline

    Plugers11

    Yeah. You can use it these if u need it for simple things, but if u want more options for arrays and so, use lambdas :)

    Lesson 2 included!
     
    Last edited: Jul 1, 2017
  4. Honestly, in my opinion, the old methods of doing these sorts of things are simpler, and easier to read and understand. I also like using methods more, as well, I find them to be more creative than what is essentially a nameless method without a class. Then there's Java 8, I'm not sure how many people are actually using it yet, but a significant amount of servers are still on Java 7 I'm sure (including many server hosts). Although, I do say I really like the default methods for interfaces added :)
     
Thread Status:
Not open for further replies.

Share This Page