Search code examples
javaguavapredicatesgoogle-guava-cache

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.


Solution

  • You can use Guava Multimaps.index method:

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

    In Java 8:

    Map<Department, List<Employee>> byName = 
        employees.stream()
                 .collect(Collectors.groupingBy(Employee::getName))
    

    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>() {
            @Override
            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 = employees.stream()
                                           .filter(e -> e.getName().equals("John Doe"))
                                           .collect(Collectors.toList());