How to sort the name along with age in java

后端 未结 8 1118
失恋的感觉
失恋的感觉 2021-01-17 23:34

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.

For example my inp

相关标签:
8条回答
  • 2021-01-17 23:55

    Currently you are a) only comparing by one attribute and b) not really making use of Java 8's new features.

    With Java 8 you can use method references and chained comparators, like this:

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

    This will compare two Person instances first by their fname and - if that is equal - by their age (with a slight optimization to thenComparingInt to avoid boxing).

    0 讨论(0)
  • 2021-01-17 23:55

    You can simply use the stream sorted method with static reference of getName and getAge methods.

    List<Person> list=new ArrayList<Person>();
    list.stream().sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).collect(Collectors.toList()).forEach(System.out::println);
    
    0 讨论(0)
  • 2021-01-17 23:59

    Your Comparator is only sorting by age, not by name.

    You could try it like that:

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

    You could also think about implementing Comparable<Person> in the Person class itself:

    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;
    
        }
    }
    
    0 讨论(0)
  • 2021-01-17 23:59

    You can use Comparator.comparing method, introduced in Java 8, returns a Comparator object that will use the specified field as the sort key.

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

    We first created two lambda expressions, one to return the age of a given person and the other to return that person’s name. We then combined these two lambda expressions in the call to the sorted() method to compare on both properties. The comparing() method created and returned a Comparator to compare based on age. On the returned Comparator we invoked the thenComparing() method to create a composite comparator that compares based on both age and name

    0 讨论(0)
  • 2021-01-18 00:05

    You need to compare for names first. If the names are the same, then and only then the result depends on comparing the age

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

    if you want to change from ascending to descending, just change the sign. e.g.

     return -comp;
    

    or swap the person

    name

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

    age

     return t1.getAge() - t.getAge();
    
    0 讨论(0)
  • 2021-01-18 00:08

    This is simple one liner comparison using ternary operator for sorting the objects. No need to write so many if/else block.

    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 讨论(0)
提交回复
热议问题