How can you filter out something from a Java ArrayList like if you have:
And the filter is "How" it will remove Joe and Mike.
One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.
ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.
To remove the duplicates from the arraylist, we can use the java 8 stream api as well. Use steam's distinct() method which returns a stream consisting of the distinct elements comparing by object's equals() method. Collect all district elements as List using Collectors. toList() .
In java-8, they introduced the method removeIf
which takes a Predicate
as parameter.
So it will be easy as:
List<String> list = new ArrayList<>(Arrays.asList("How are you", "How you doing", "Joe", "Mike")); list.removeIf(s -> !s.contains("How"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With