JavaRush /Java Blog /Random EN /Stop writing cycles! Top 10 best methods for working with...

Stop writing cycles! Top 10 best methods for working with collections from Java 8

Published in the Random EN group
I think there is no need to explain to JavaRush students what collections are and what they are for. However, after the release of the 8th version, many elementary operations, which previously took 6-7 lines of code, were simplified to the minimum. Without further ado, here are the top 10 best Java8 Collections Framework techniques that will save you tons of time and space! Stop writing cycles!  Top 10 best methods for working with collections from Java 8 - 1Hello everyone, friends! Habit, as you know, is second nature. And having gotten used to writing, for (int i = 0; i <......)I don’t want to relearn it at all (especially since this design is quite simple and understandable). However, inside loops we often repeat the same elementary operations, the repetition of which we would really like to get rid of. With the release of Java8, Oracle decided to help us with this. Below are the 10 best collection methods that will save you a ton of time and code.

1. Iterable.forEach(Consumer<? super T> action)

The name speaks for itself. Iterates through the passed collection and executes a lambda expression actionfor each element.
List <Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
numbers.forEach(s -> System.out.print(s + " "));
1 2 3 4 5 6 7

2. Collection.removeIf(Predicate<? super E> filter)

Nothing complicated either. The method iterates through the collection and removes those elements that match filter.
List <Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
numbers.removeIf(s -> s > 5);
 numbers.forEach(s -> System.out.print(s + " "));
In one line we remove from the list all numbers greater than 5.

3. Map.forEach(BiConsumer<? super K, ? super V> action)

The method forEachworks not only for classes that implement the interface Collection, but also for Map.
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));
Название книги: Братья Карамазовы. Author: Федор Достоевский
Название книги: Философия Java. Author: Брюс Эккель
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Властелин Колец. Author: Джон Толкин

4. Map.compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)

It looks a little more intimidating, but in reality it is simple, like all the previous ones. For the specified key key, this method sets value to the result of the function remappingFunction. For example:
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));

books.compute("Философия Java", (a,b) -> b+", крутой чувак");
System.out.println("_______________________");
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));
Название книги: Братья Карамазовы. Author: Федор Достоевский
Название книги: Философия Java. Author: Брюс Эккель
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Властелин Колец. Author: Джон Толкин
_______________________
Название книги: Братья Карамазовы. Author: Федор Достоевский
Название книги: Философия Java. Author: Брюс Эккель, крутой чувак
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Властелин Колец. Author: Джон Толкин
The author of " Java Philosophy " is definitely cool! :)

5. Map.computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

The method will add a new element to the Map , but only if the element with the same key is not there. The result valueof the function execution will be assigned to it mappingFunction. If an element with such a key already exists, it will not be overwritten, but will remain in place. Let's go back to our books and try a new method:
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

books.computeIfAbsent("Гарри Поттер и узник Азкабана", b -> getHarryPotterAuthor());
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));
Our function mappingFunction:
public static String getHarryPotterAuthor() {
        return "Джоан Роулинг";
    }
And here is the new book:
Название книги: Братья Карамазовы. Author: Федор Достоевский
Название книги: Философия Java. Author: Брюс Эккель
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Гарри Поттер и узник Азкабана. Author: Джоан Роулинг
Название книги: Властелин Колец. Author: Джон Толкин

6. Map.computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Same principle as , Map.compute()but all calculations will only be performed if the element with the key keyalready exists.
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

books.computeIfPresent("Евгений Онегин", (a,b) -> b="Александр Пушкин");
System.out.println("_________________");
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));
books.computeIfPresent("Братья Карамазовы", (a,b) -> b="Александр Пушкин");
System.out.println("_________________");
books.forEach((a,b) -> System.out.println("Название книги: " + a + ". Author: " + b));
When the function was called for the first time, no changes occurred, because Mapthere is no book with the title “Eugene Onegin” in ours. But for the second time the program changed the author for the book “The Brothers Karamazov” to “Alexander Pushkin”. Conclusion:
_________________
Название книги: Братья Карамазовы. Author: Федор Достоевский
Название книги: Философия Java. Author: Брюс Эккель
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Властелин Колец. Author: Джон Толкин
_________________
Название книги: Братья Карамазовы. Author: Александр Пушкин
Название книги: Философия Java. Author: Брюс Эккель
Название книги: Преступление и наказание. Author: Федор Достоевский
Название книги: Война и мир. Author: Лев Толстой
Название книги: Властелин Колец. Author: Джон Толкин

7. Map.getOrDefault(Object key, V defaultValue)

Returns the value corresponding to the key key. If such key does not exist, returns the default value.
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

String igor = books.getOrDefault("Слово о полку Игореве", "Неизвестный автор");
System.out.println(igor);
Very comfortably:
Неизвестный автор

8. Map.merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

I didn't even try to calculate how many lines of code this method will save you.
  • MapIf the key keydoes not exist in yours , or valuefor this key it is equal , nullthe method adds .Mapkey-value
  • If the key Keyexists and it is there, value != nullthe method changes it valueto the result of executing the passed function remappingFunction.
  • If remappingFunctionit returns null, keyit is removed from the collection.
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

books.merge("Философия Java", "Брюс Эккель", (a, b) -> b +  " и кто-то там еще");
books.forEach((a,b) -> System.out.println("Название:" + a + ". Author: " + b));
Conclusion:
Название:Братья Карамазовы. Author: Федор Достоевский
Название:Философия Java. Author: Брюс Эккель и кто-то там еще
Название:Преступление и наказание. Author: Федор Достоевский
Название:Война и мир. Author: Лев Толстой
Название:Властелин Колец. Author: Джон Толкин
*sorry Bruce*

9. Map.putIfAbsent(K key, V value)

Previously, to add a pair to Mapif it was not there, you had to do the following:
Map <String, String> map = new HashMap<>();
if (map.get("Властелин Колец") == null)
    map.put("Властелин Колец", "Джон Толкин");
Now everything has become much simpler:
Map<String, String> map = new HashMap<>();
map.putIfAbsent("Властелин Колец", "Джон Толкин");

10. Map.replace and Map.replaceAll()

Last on the list, but not least. Map.replace(K key, V newValue— replaces the key value keywith newValue, if such a key exists. If not, nothing happens. Map.replace(K key, V oldValue, V newValue)- does the same thing, but only if the current value keyis oldValue. Map.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)— replaces all values value​​with the result of function execution function. For example:
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

books.replace("Братья Карамазовы", "Брюс Эккель", "Джон Толкин");
books.forEach((a,b) -> System.out.println("Название:" + a + ". Author: " + b));
Название:Братья Карамазовы. Author: Федор Достоевский
Название:Философия Java. Author: Брюс Эккель
Название:Преступление и наказание. Author: Федор Достоевский
Название:Война и мир. Author: Лев Толстой
Название:Властелин Колец. Author: Джон Толкин
Did not work! The current value of the Brothers Karamazov key is Fyodor Dostoevsky, not Bruce Eckel, so nothing has changed.
Map <String, String> books = new HashMap<>();
books.put("Война и мир", "Лев Толстой");
books.put("Преступление и наказание", "Федор Достоевский");
books.put("Философия Java", "Брюс Эккель");
books.put("Братья Карамазовы", "Федор Достоевский");
books.put("Властелин Колец", "Джон Толкин");

books.replaceAll((a,b) -> getCoolWriter());
books.forEach((a,b) -> System.out.println("Название:" + a + ". Author: " + b));
public static String getCoolWriter() {
        return "Крутой писатель";
    }
Название:Братья Карамазовы. Author: Крутой писатель
Название:Философия Java. Author: Крутой писатель
Название:Преступление и наказание. Author: Крутой писатель
Название:Война и мир. Author: Крутой писатель
Название:Властелин Колец. Author: Крутой писатель
Easily changed the values ​​for the entire Map without any complex constructions! PS Getting used to something new is always difficult, but these changes are really good. In any case, some parts of my code are now definitely less spaghetti-like than before :) If you liked the article and would like to see new ones, do not forget to support the author in the competition by clicking “Like”, or better yet, “Like” :) Good luck with your studies!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION