JavaRush /Java Blog /Random EN /Lambdas and streams, only practice, no theory

Lambdas and streams, only practice, no theory

Published in the Random EN group
Hi all. On the occasion of the competition, I decided to write not an article here, but a short lesson. It will be about lambdas and streams in Java. If you are already familiar and use them, then skip straight to the end of the article, there will be a small selection of tasks with JavaRush on which you can practice. You need java 8 and higher, training from JR, there will be few details and a lot of incomprehensible things, a strong desire to figure it out. Let's start with the fact that I will not explain the history of the appearance of lambdas and streams, I just don’t know it myself. I only know that they came from the functional programming style, to our OOP style. In my short learning experience, I simply showed how and what, some people find it difficult to understand the idea, so just remember how to write, you will understand later.

Lambdas

Lambdas and streams, only practice, no theory - 1Lambdas and streams, only practice, no theory - 2If you don’t know what lambdas are at all, then: A lambda looks like this:
(a, b) -> a.compareTo(b)
(переменные) -> действие
That's enough for now. You can read the theory here: link one , link two , but I think practice is much more fun. I suggest you solve the following problem: Write a calculator using method 1. The method should accept 2 digital values ​​and something else. Your code will look something like this:
class Lambda{
    public static void main (String[] args) {
	}

    public static double calculate(){
       	return null;
    }
}
You need to enter 3 parameters in the method signature calculate, add 1 command in returnand test calling this method in main. What should this method be able to do?
  • fold;
  • multiply;
  • divide;
  • subtract;
  • calculate the root;
  • raise to a power;
  • raise to a power the sum of arguments divided by the first number + 117;
  • and all any other operations you can think of.
What not to use:
  • if-else;
  • charas an operation indicator;
  • switch-case;
  • and everything else that comes to your mind.
What you can use:
  • Only lambdas, the task is on them.
- What? And it's all? - Yes, that’s all, because you literally need to add 3 lines, if I suggest at least one, the rest will be written automatically. And if you want, you can google examples and try to understand. Of course, you will check yourself and if you cheat, no one will know, but then why? Having solved such a simple problem, all of my 1.5 students gained a rough understanding of what lambdas are and how to use them. This will be very necessary for streaming. If you want to brag about the result and find out if you did it right, send the code in a private message. There is no need to comment; you can add interesting tips there (but in such a way as not to make the task too easy). Again, having solved this example, you should already have a rough understanding of how to use lambdas.
Lambdas and streams, only practice, no theory - 3
Now let's move on to java streams. These are not the streams that you, the reader, may have thought about. No it's not inputStreamand it's not OutputStream. It's different, it's more interesting. Streams have replaced cycles, not completely, but still. They are served with the motto “don’t explain how to do it, explain what to do.” A small example of a stream:
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList.stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);
What's going on here? Let's add comments:
myList.stream() // получить поток
    .filter(s -> s.startsWith("c")) //отфильтровать значения, оставить те, что начинаются с «с»
    .map(String::toUpperCase)  // преобразовать все значения, перевести в верхний регистр
    .sorted() // отсортировать по порядку (дефолтный порядо)
    .forEach(System.out::println); // вывести каждый элемент на экран
Compare with a regular loop:
List<String> toSort = new ArrayList<>();
for(String s : myList){
     if(s.startsWith("c")){
         toSort.add(s.toUpperCase());
     }
}

Collections.sort(toSort);

for(String s : toSort){
     System.ouy.println(s);
}
When you read the code, everything looks scary, but is it easier with comments? This is normal, I didn’t understand them for a long time either. The key to understanding is practice. Therefore, we begin to read third-party articles and look for answers to our questions, you can also ask them here in the comments, I won’t give a full answer, but I will point in the direction. List of tasks from JavaRush that I think are great for practicing streaming:
  • 2208 - can be solved with 1 stream and 1 return, i.e. the body of the method will begin with returnand then there will be 1 whole stream. Let's omit the requirement StringBuilder.

  • 1908 - you can also solve it with 1 stream and 1 return. Starting with reading the file. I don’t know how to record to a file via streams (if this is possible), for now we do it manually. Those. We open only 2 streams (console and writing to a file). We read the file through methods that will return us either a sheet or a stream (google and javadoc).

  • 1907 - in theory, it can also be solved in one stream. The input to the stream is the file name, the output is the number of words world.

That's all. If I can, I’ll write another simple story. In my opinion, reading about something cool without the opportunity to try it is somehow boring or something. And after the calculator and 3 puzzles, I think you’re already getting along well with lambdas and streams, so read about all the possibilities if you haven’t already. UPD:
  • 1016 - in a slightly perverted way, you can solve it in 1 stream and 1 return;

  • 1821 - very easy and in 1 stream and 1 return.

    These 2 tasks will introduce you to another streaming method and another collector.

  • 1925 - you can get a line with words in one stream and then write it to a file (I don’t know if it’s possible to write to a file from a stream)

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION