Java remove elements from collection by filtering

One of the way to remove elements of collection (in this example list) is to use method removeIf Method declaration: default boolean removeIf(Predicate<? super E> filter) Description: Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller. … Read more

Java asymmetric set difference

If you need to find difference between two sets you can use method removeAll. The difference will be kept only on the set which is calling the method. Definition: booleanremoveAll(Collection<?> c) Description: Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a … Read more

Java intersection of Sets

If you need to get only the elements which are common for two sets you can use the method retainAll. The documentation for this method states: “Method signature: boolean retainAll(Collection<?> c) Description: Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all … Read more

Java 17 sort (Comparable) with lambda and Record

In this example we can see record Person and we use stream’s sorted(Comparator<? super T> comparator) method to sort the List of people by their age. So sorted(Comparator<? super T> comparator) accept as parameter Comparator. For this reason we have to create Comparator and we sort inside by age. The documentation for sorted(Comparator<? super T> comparator) state: Returns … Read more

Java List indexOf method

There is a very important method indexOf which is part of the List interface. The description in Java documentation states: “Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or … Read more

Java 17 do-while loop of user input with switch statement

In this program, you can see Java 17 multi-string (inputMessage) creating BufferedReader to read the user input (System.in). The user input inside the do-while loop will be checked and repeated until the user writes exit. For every input 1, 2, or 3 there is an specific output, but for other user inputs we get the … Read more