JavaRush /Java Blog /Random EN /Stop writing cycles! Top 10 Best Practices for Working wi...

Stop writing cycles! Top 10 Best Practices for Working with Collections from Java 8

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

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

The name speaks for itself. Iterates over the given 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 fact it is simple, like all the previous ones. For the specified key key, this method sets value to the result of executing 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 there is no element with that key. As valueit will be assigned the result of the execution of the function mappingFunction. If there is already an element with this key, 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 y 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 name "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 no such key exists, 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 did not even try to calculate how many lines of code this method will save you.
  • If Mapthe key keydoes not exist in yours, or valueit is equal for this key null, the method adds to Mapthe passed pair key-value.
  • If the key Keyexists and it is, 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 easier:
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 value of the key keywith newValueif such a key exists. If not, nothing happens. Map.replace(K key, V oldValue, V newValue)- does the same, 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 the 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 Dostoyevsky, 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 complicated constructions! Stop writing cycles!  Top 10 Best Practices for Working with Collections from Java 8 - 2PS It's never easy to get used to something new, but these changes are really good. Anyway, 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, don't forget to support the author in the contest by clicking "Like", or better - "Lovely" :) Successes in training!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION