题解 | #集合排序#

集合排序

https://www.nowcoder.com/practice/4d12899bb255459bbf2b3635b3d32817

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Comparator;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Customer customer1 = new Customer("小明", scanner.nextInt());
        Customer customer2 = new Customer("小军", scanner.nextInt());
        Customer customer3 = new Customer("小红", scanner.nextInt());
        List<Customer> customers = new ArrayList<>();
        customers.add(customer1);
        customers.add(customer2);
        customers.add(customer3);

        //write your code here......
        customers = customers.stream()
                .sorted(Comparator.comparingInt(Customer::getConsumption).reversed())
                .collect(Collectors.toList());

        System.out.println(customers);

    }
}

class Customer implements Comparable<Customer> {
    private String name;
    private int consumption;

    public Customer(String name, int consumption) {
        this.name = name;
        this.consumption = consumption;
    }

    @Override
    public String toString() {
        return "Customer{" +
               "name='" + name + '\'' +
               ", consumption=" + consumption +
               '}';
    }

    //write your code here......
    @Override
    public int compareTo(Customer customer) {
        return this.consumption -  customer.consumption;
    }

    public int getConsumption() {
        return consumption;
    }
}

全部评论

相关推荐

07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务