Can I use compareTo to sort integer and double values?

后端 未结 4 2036
天命终不由人
天命终不由人 2020-12-10 03:52

Can I use compareTo to sort integer and double values? My system gives me an error that I Cannot invoke compareTo(int) on the primitive type int. any ideas?

Code:

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 04:24

    Step 1: Sort list by last name (for String values)

    Collections.sort(peopleList, (p1, p2) -> 
                         p1.getLastName().compareTo(p2.getLastName()));
    

    Step 2: Print all elements in the list

    for (People ppl : peopleList) {
        System.out.print(ppl.getFirstName()+" - "+ppl.getLastName());
    }
    

    Step 1: Sort list by Age (for int values)

    Collections.sort(peopleList, (p1, p2) -> p1.getAge() - (p2.getAge()));
    

    Step 2: Print all elements in the list

    for (People ppl : peopleList) {
        System.out.println(ppl.getAge());
    }
    

提交回复
热议问题