title: How to sort the name along with age in java
body: <p>I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.</p>
  
  <p>For example my input is</p>
  
  <pre><code>tarun  28
  arun   29
  varun  12
  arun   22
  </code></pre>
  
  <p>and the output should be</p>
  
  <pre><code>arun   22
  arun   29
  tarun  28
  varun  12
  </code></pre>
  
  <p>But I get something like</p>
  
  <pre><code>varun  12
  arun   22
  tarun  28
  arun   29
  </code></pre>
  
  <p>Means it's sorted either only by ages or names.</p>
  
  <p>This is the code which is implemented:</p>
  
  <p>POJO class:</p>
  
  <pre><code>class Person {
  
      String fname;
  
      int age;
  
      public Person() {
      }
  
      public int getAge() {
          return age;
      }
  
      public void setAge(int age) {
          this.age = age;
      }
  
      public String getFname() {
          return fname;
      }
  
      public void setFname(String fname) {
          this.fname = fname;
      }
  
      public Person(String fname,  int age) {
          this.fname = fname;
  
          this.age = age;
      }
  
      @Override
      public String toString() {
          return fname  + age;
      }
  }
  </code></pre>
  
  <p>Test class:</p>
  
  <pre><code>public class Test {
  
      public static void main(String[] args) {
          List&lt;Person&gt; persons = new ArrayList&lt;&gt;();
          persons.add(new Person("tarun", 28));
          persons.add(new Person("arun", 29));
          persons.add(new Person("varun", 12));
          persons.add(new Person("arun", 22));
  
          Collections.sort(persons, new Comparator&lt;Person&gt;() {
  
              @Override
              public int compare(Person t, Person t1) {
                  return t.getAge() - t1.getAge();
              }
          });
          System.out.println(persons);
  
      }
  }
  </code></pre>