With each new version of Java it becomes richer and richer. While much of the richness lies in earlier versions, the language has continued to improve in both methodology and implementation. Collections in Java are no exception. The core collections framework appeared in J2SE 1.2 and continued to evolve, undergoing changes that were more pleasing than disappointing. With the release of JDK 5, collections have become more convenient, faster, and easier to work with. This led to the fact that programmers began to exploit them more intensively. Certain patterns have been developed for working with them, which are without any doubt effective. But with JDK 8, collections got better again, and they got better thanks to threads. Obviously, due to the fact that the collection can be represented in the form of streams, the methodology for working with them will also change. Therefore, I want to show how familiar and understandable solutions with collections become even simpler.
- Example 1. It couldn’t be simpler
- Example 2. Find even values in the list and display them in the console
- Example 3. Let's count how many words in the list are 5 characters long
- Example 4. Print unique words
- Example 5. Long words
- Example 6. Words with numbers
- Example 7. Selecting numbers
Example 1. It couldn’t be simpler
Of course, let's start with the simplest thing, let's go through all the elements of the collection and display all the elements.// создадим и заполним список
List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 5, 6, 11, 3, 15, 7, 8);
// а теперь
// быстрый for по всем elementм, только для коллекций
for (Integer i:list){
System.out.println(i);
}
//но мы уже живем в JDK 8
//а значит нужно так
list.stream().forEach(System.out::println);
As you noticed, there is a new syntax that, in my opinion as a Java newbie, is much simpler. So, what is visible in the new syntax:
берем_список(list).превращаем_в_поток(stream).перебираем_все_элементы(forEach)(тут_интуитивно_понятно)
System.out::println
— a link to a static method that outputs a string to the console Instead of a link to a static method, you can use a slightly different, less clear entry:
list.stream().forEach(i -> System.out.println(i));
This entry uses lambda expressions. And yes, to learn how to work with streams, you will need to learn lambda expressions - they are wonderful. Further, I will not show how to work with collections using only streams, relying on the fact that you became familiar with traditional methods during the course.
Example 2. Find even values in the list and display them in the console
list.stream().filter(i -> i%2==0).forEach(System.out::println);
The whole problem was solved in one line. I hope you enjoy working in one line. Using the method, filter
we filtered the stream and output what was left to the console. The filter is a very powerful thing that can help in the most unexpected cases. Let's get creative and change the conditions of the problem. For example, we need to count how many even numbers are in the list:
long count = list.stream().filter(i -> i%2==0).count();
And again in one line. Somehow everything seems simple. In the filter, we used a lambda expression, thereby placing only even numbers in the new stream, and then applied to the new stream count
, which counted how many elements are in the new stream.
Example 3. Let's count how many words in the list are 5 characters long
We've played with integers, now let's play with words.List<String> list = new ArrayList<>();
Collections.addAll(list, "разые", "слова", "интересные", "And", "Not", "Very");
System.out.println(list.stream().filter(w -> w.length() == 5).count());
We used the filter again. In the filter, using a lambda expression, a new stream was displayed, and then, understandably, count
I calculated how many elements were in the new stream.
Example 4. Print unique words
A familiar task when we read many different words into a collection from a file, and now we only need unique ones.List<String> list = new ArrayList<>();
Collections.addAll(list, "Vasya", "Таня", "Olya", "Vasya", "Olya", "Сергей");
list.stream().distinct().forEach(System.out::println);
The main action was done on the stream using distinct
. Next, I suggest taking a look at some of our tasks from the course using threads
Example 5. Long words
At the 9th level of Java Core, in lecture 11 there is an interesting problem, in it you need to write words separated by commas in File2, the length of which is strictly greater than 6. No matter what kind of garden you are fencing, I propose the following solution:-
From the source file we read all the words into the list.
-
Then we execute the following line
Optional<String> rezult = list.stream() .filter(w->w.length()>6) .reduce((w1,w2)->w1+", "+w2);
-
result.get()
write to a file.
Example 6. Words with numbers
Write all words that contain numbers, for example, a1 or abc3d, separated by a space in File2. This is also a condition from our problem book, as you guessed, the solution is simple.Optional<String> rezult = list.stream()
.filter(w->w.matches(".*?\\d+.*?"))
.reduce((w1,w2)->w1+" "+w2);
We filtered the stream using a regular expression, and then reduce and a lambda expression. So much in common with the previous task.
Example 7. Selecting numbers
The whole task sounds like this:- Read 2 file names from the console.
- Output into the second file all the numbers that are in the first file.
- Numbers are separated by spaces.
- Close streams.
Optional<String> rezult = list.stream().filter(w->w.matches("\\d+"))
.reduce((w1,w2)->w1+" "+w2);
System.out.println(rezult.get());
Using threads, the problem is solved in a very simple way. But, lo and behold, compare this solution with the two previous ones yourself. Concluding the article, I want to confess to you: guys, I cheated when I selected examples. The fact is that I chose the simplest examples in order to show you an unfamiliar topic using familiar problems. Of course, threads are used for both simple and more complex tasks. But as Horstman emphasized in his book, “Data flows operate on the principle of “what, not how to do.”,” which means many previously complex tasks can become simpler. I don’t know about you, but I liked the flows, I hope I didn’t discourage you from learning them. And let me explain one more thing:
- I did not set out to teach the reader how to use streams in collections; I am not that experienced a teacher. I wanted to show you that threads are simple and very interesting! In general, this is a necessity.
- The more I understand flows, the more I see problems where they solve all the problems from the course book, which means that flows were not invented in vain.
- Streams are not only easy to work with, but they also have an important advantage - when working with large amounts of data, streams are often more productive.
GO TO FULL VERSION