前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java-comparator

java-comparator

作者头像
luxuantao
发布2021-02-24 11:24:18
5200
发布2021-02-24 11:24:18
举报
文章被收录于专栏:Fdu弟中弟Fdu弟中弟
要使自己的类拥有排序功能,就要实现comparator接口,重写compare方法。

原题链接:Java Comparator

Comparators are used to compare two objects. In this challenge, you’ll create a comparator and use it to sort an array.

The Player class is provided for you in your editor. It has fields: a String and a integer.

Given an array of Player objects, write a comparator that sorts them in order of decreasing score; if or more players have the same score, sort those players alphabetically by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.

Sample Input

代码语言:javascript
复制
5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150

Sample Output

代码语言:javascript
复制
aleksa 150
amy 100
david 100
aakansha 75
heraldo 50

代码如下:

代码语言:javascript
复制
import java.util.*;

class Checker implements Comparator<Player> {
    @Override
    public int compare(Player p1, Player p2) {
        if (p2.score == p1.score) {
            return p1.name.compareTo(p2.name);
        } else {
            return p1.score > p2.score ? -1 : 1;    
        }
    }
}

class Player {
    String name;
    int score;
    
    Player(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        Player[] player = new Player[n];
        Checker checker = new Checker();
        for(int i = 0; i < n; i++) {
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();  
        Arrays.sort(player, checker);
        for(int i = 0; i < player.length; i++) {
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}

知识点补充:

  1. String类有个compareTo()函数,前者比后者小时返回负数。
  2. public int compare(Player p1, Player p2)返回负数时,不换位置。
  3. 注意用法:Arrays.sort(player, checker);

原题链接:Java Sort

You are given a list of student information: ID, FirstName, and CGPA. Your task is to rearrange them according to their CGPA in decreasing order. If two student have the same CGPA, then arrange them according to their first name in alphabetical order. If those two students also have the same first name, then order them according to their ID. No two students have the same ID.

Sample Input

代码语言:javascript
复制
5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75
22 Fahim 3.76

Sample Output

代码语言:javascript
复制
Ashis
Fahim
Samara
Samiha
Rumpa

代码如下:

代码语言:javascript
复制
import java.util.*;

class Student{
   private int id;
   private String fname;
   private double cgpa;
   public Student(int id, String fname, double cgpa) {
      super();
      this.id = id;
      this.fname = fname;
      this.cgpa = cgpa;
   }
   public int getId() {
      return id;
   }
   public String getFname() {
      return fname;
   }
   public double getCgpa() {
      return cgpa;
   }
}

class StudentComparator implements Comparator<Student>{
	@Override
	public int compare(Student s1, Student s2) {
		double cgpa1 = s1.getCgpa();
		double cgpa2 = s2.getCgpa();
		if(Math.abs(cgpa1 - cgpa2)<0.00000001){
			int fnameCom = s1.getFname().compareTo(s2.getFname());
			if(fnameCom==0)	return s1.getId()-s2.getId(); 
			else return fnameCom;
		}
		else return (cgpa1<cgpa2)?1:-1;
	}
}

public class Solution
{
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		int testCases = Integer.parseInt(in.nextLine());
		List<Student> studentList = new ArrayList<Student>();
		while(testCases>0){
			int id = in.nextInt();
			String fname = in.next();
			double cgpa = in.nextDouble();
			Student st = new Student(id, fname, cgpa);
			studentList.add(st);
			testCases--;
		}
		Collections.sort(studentList, new StudentComparator());
		for(Student st: studentList){
			System.out.println(st.getFname());
		}
	}
}

知识点补充:

这题用了容器ArrayList,所以重写好Comparator接口后,排序时要用Collections.sort(studentList, new StudentComparator());

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-09-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档