题解 | #集合排序#

集合排序

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

全部评论

相关推荐

代码飞升_不回私信人...:别这样贬低自己,降低预期,放平心态,跟昨天的自己比。做好自己,反而会效率更高心态更好,加油兄弟
点赞 评论 收藏
分享
11-13 10:17
门头沟学院 Java
昨天面美团,jvm,juc问的好深啊,感觉小林coding不太够喔,牛油们有没有什么推荐的八股网站嘛🕒&nbsp;岗位/面试时间👥&nbsp;面试题目🤔&nbsp;面试感受
明天不下雨了:小林Coding:https://xiaolincoding.com/ 全栈哥:https://www.pdai.tech/ Guide哥:https://javaguide.cn/ 秀哥:https://interviewguide.cn/ 沉默王二:https://javabetter.cn/home.html 磊哥:https://www.javacn.site/interview/basic/ 小傅哥:https://bugstack.cn/ 源码哥:https://doocs.github.io/source-code-hunter/#/ 各大厂的公众号技术文章和一些经典的书籍
面试太紧张了怎么办?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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