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

Java read input from console

To capture input from console in Java program you have several options. Two of the most commons ones are to use Scanner (java.util.Scanner) or BufferedReader (java.io.BufferedReader). Both of them are using System.in (standard input stream) to capture the keyboard input. ⚠ One thing to consider is that both classes Scanner and BufferedReader implement Closeable (java.io.Closeable). … Read more