How to sort name with age in java

I am new to Java 8. I just want to sort by name. But the condition: if there are duplicate names, then it should be sorted according to age.

For example, my input

tarun  28
arun   29
varun  12
arun   22

and the exit should be

arun   22
arun   29
tarun  28
varun  12

But I get something like

varun  12
arun   22
tarun  28
arun   29

Means that it is sorted only by age or name.

This is the code that is implemented:

POJO Class:

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;
    }
}

Testing Class:

public class Test {

    public static void main(String[] args) {
        List<Person> persons = new ArrayList<>();
        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<Person>() {

            @Override
            public int compare(Person t, Person t1) {
                return t.getAge() - t1.getAge();
            }
        });
        System.out.println(persons);

    }
}
+7
source share
6 answers

You are currently a) comparing only one attribute and b) not using Java 8 new features.

With Java 8, you can use method references and chain comparators, for example:

Collections.sort(persons, Comparator.comparing(Person::getFname)
    .thenComparingInt(Person::getAge));

Person fname - - age ( thenComparingInt, ).

+6

, compare .

compare , , , , . , .

:

  • t.getFname().compareTo(t1.getFname())
  • ,
  • .

Integer.compare, .. Integer.compare(t.getAge(), t1.getAge()).

+3

. ,

public static void main(String[] args) {
    List<Person> persons = new ArrayList<>();
    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<Person>() {

        public int compare(Person t, Person t1) {
            int comp = t.getFname().compareTo(t1.getFname());
            if (comp != 0) {    // names are different
                return comp;
            }
            return t.getAge() - t1.getAge();
        }
    });
    System.out.println(persons);

}}

, . .

 return -comp;

 int comp = t1.getFname().compareTo(t.getFname());

 return t1.getAge() - t.getAge();
+3

Comparator , .

:

new Comparator<Person>() {
    @Override
    public int compare(Person t, Person t1) {
        int ret = t.getFname().compareTo(t1.getFname());
        if (ret == 0) {
           ret = Integer.compare(t.getAge(), t1.getAge()); 
        }
        return ret;
    }
}

Comparable<Person> Person:

class Person implements Comparable<Person> {
    @Override
    public int compareTo(Person p) {
        int ret = fname.compareTo(p.fname);
        if (ret == 0) {
           ret = Integer.compare(age, p.getAge()); 
        }
        return ret;

    }
}
+1

. if/else.

Collections.sort(persons, new Comparator<Person>() {

    @Override
    public int compare(Person t1, Person t2) {

        return t1.getFname().equals(t2.getFname()) ? t1.getAge()-t2.getAge() : t1.getFname().compareTo(t2.getFname());

    }
});
0

Comparator.comparing, Java 8, Comparator, .

final Function<Person, Integer> byAge = person -> person.getAge();   
final Function<Person, String> byTheirName = person -> person.getFname();
System.out.println("Sorted in ascending order by age and name: ");
        List<Person> sortedlist =   people.stream()
            .sorted(Comparator.comparing(byAge).thenComparing(byTheirName))
            .collect(Collectors.toList());
        sortedlist.forEach(System.out::println);

First, we created two lambda expressions , one of which returns the age of a given person, and the other - the name of that person. Then we combined these two lambda expressions in a method call sorted()to compare both properties. The method comparing()created and returned Comparator for comparison by age. In the returned comparator, we have a thenComparing()method thenComparing()for creating a composite comparatorthat compares both by age and by name.

0
source

Source: https://habr.com/ru/post/1684020/


All Articles