Krieger Krieger - 1 year ago 138
Java Question

How to get duplicate elements in array list using guava predicates

I have a array with set of elements. I need to find the duplicate elements in that array by comparing particular field using guava predicated in java.

For example:

I have an arraylist with set of employees details. I need to find details of employees with same name.

Answer Source

You can use Guava Multimaps.index method:

ImmutableListMultimap<String, Employee> byName = 
  Multimaps.index(employees, new Function<Employee, String>(){
      public String apply(Employee e) {
          return e.getName();

In Java 8:

Map<Department, List<Employee>> byName =

Regarding your comment, it seems that you want to filter the list to keep only employees with a specific name.

So using Guava:

List<Employee> employees = // ...
Collection<Employee> filtered = 
    Collections2.filter(employees, new Predicate<Employee>() {
        public boolean apply(Employee e) {
            return e.getName().equals("John Doe");
// if you want a List:
List<Employee> filteredList = new ArrayList<>(filtered);

Using Java 8:

List<Employee> filteredList =
                                       .filter(e -> e.getName().equals("John Doe"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download