Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList filter [duplicate]

How can you filter out something from a Java ArrayList like if you have:

  1. How are you
  2. How you doing
  3. Joe
  4. Mike

And the filter is "How" it will remove Joe and Mike.

like image 787
kevc45 Avatar asked Feb 05 '12 01:02

kevc45


People also ask

How do you find duplicates in ArrayList?

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.

Can Arraylists have duplicates?

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.

How do you remove duplicates from an ArrayList in Java 8?

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() .


1 Answers

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")); 
like image 168
Alexis C. Avatar answered Oct 15 '22 12:10

Alexis C.