title: java 8 stream for sorting a list of objects based on particular field
body: <p>I have a scenario to sort the objects based on timestamp. The classes are as follows:</p>
  
  <pre><code>class Employee 
  {
      private String name;
      private List&lt;Address&gt; addresses;
  
      //...
      //Getters and setters for all fields
  }
  
  public class Address
  {
      private String city;
      private Timestamp startDate;
      private Timestamp endDate;
      private String typeOfResidence;
  
      //...
      //Getters and setters for all the fields
  }
  </code></pre>
  
  <p>For an employee, there are 2 possibilities 
  1. it will have a list of address.
  2. the list of address can be null</p>
  
  <p>The address class has a field <code>typeOfResidence</code> which can have values such as Residence, Office, ForeignHome.</p>
  
  <p>Each <code>Employee</code> can have list of address, one address will be Residential, other Office and so on. There can be multiple Residential addresses but only one Office address.</p>
  
  <p>I want to sort the list of employees based on startDate of Address whose typeOfResidence=Office. </p>
  
  <p>I have written the following code:</p>
  
  <pre><code>private void sortEmployeeListBasedOnStartDate(List&lt;Employee&gt; employeeList)
  {
      Comparator&lt;Address&gt; byTimeStamp = Comparator.comparing(
          Address::getStarteDate,
          (ts1, ts2) -&gt; ts1.toGregorianCalendar().compareTo(ts2.toGregorianCalendar())
      );
  
      employeeList.stream()
          .map(x -&gt; getLatestAddressByType(x, "Office"))
          .filter(y -&gt; y!=null)
          .sorted(byTimeStamp.reversed())
          .collect(Collectors.toList());
  }
  
  public Address getLatestAddressByType(Employee employee, String type)
  {
      if(role != null &amp;&amp; brokerageManagedProposalType != null)
      {
           return getUserAddress(employee).stream()
              .filter(address-&gt; address.getTypeOfResidence().equals(type))
              .findFirst()
              .orElse(null);
      }
      return null;
  }
  
  public List&lt;Address&gt; getUserAddress(Employee employee)
  {
      if (!NullChecker.isNull(employee) &amp;&amp; !NullChecker.isNull(employee.getAddress()))
      {
          return employee.getAddress();
      }
      return Collections.emptyList();
  }
  </code></pre>
  
  <p>Somehow this does not seem to be working. The employees are not sorted. Please help me to make it working.</p>