java集合比较器_比较器接口-Java集合

java集合比较器

In Java, Comparator interface is used to order(sort) the objects in the collection in your own way. It gives you the ability to decide how elements will be sorted and stored within collection and map.

在Java中,Comparator接口用于以您自己的方式对集合中的对象进行排序(排序)。 它使您能够决定如何在集合和映射中对元素进行排序和存储。

Comparator Interface defines compare() method. This method has two parameters. This method compares the two objects passed in the parameter. It returns 0 if two objects are equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is returned. The method can throw a ClassCastException if the type of object are not compatible for comparison.

比较器接口定义了compare()方法。 此方法有两个参数。 此方法比较参数中传递的两个对象。 如果两个对象相等,则返回0。 如果object1大于object2,它将返回一个正值。 否则,返回负值。 如果对象类型不兼容以进行比较,则该方法可以引发ClassCastException

使用比较器界面的规则 (Rules for using Comparator interface)

Rules for using Comparator interface:

使用比较器界面的规则:

  1. If you want to sort the elements of a collection, you need to implement Comparator interface.

    如果要对集合的元素进行排序,则需要实现Comparator接口。

  2. If you do not specify the type of the object in your Comparator interface, then, by default, it assumes that you are going to sort the objects of type Object. Thus, when you override the compare() method ,you will need to specify the type of the parameter as Object only.

    如果未在Comparator界面中指定对象的类型,则默认情况下,它将假定您将对Object类型的对象进行排序。 因此,当您覆盖compare()方法时,您需要将参数的类型指定为“仅对象”。

  3. If you want to sort the user-defined type elements, then while implementing the Comparator interface, you need to specify the user-defined type generically. If you do not specify the user-defined type while implementing the interface,then by default, it assumes Object type and you will not be able to compare the user-defined type elements in the collection

    如果要对用户定义的类型元素进行排序,则在实现Comparator接口时,需要一般性地指定用户定义的类型。 如果在实现接口时未指定用户定义的类型,那么默认情况下它将假定为对象类型,并且您将无法比较集合中用户定义的类型元素

For Example:

例如:

If you want to sort the elements according to roll number, defined inside the class Student, then while implementing the Comparator interface, you need to mention it generically as follows:

如果要根据在Student类中定义的卷编号对元素进行排序,则在实现Comparator接口时,需要一般性地提及它,如下所示:

class MyComparator implements Comparator<Student>{}

If you write only,

如果只写

class MyComparator implements Comparator {}

Then it assumes, by default, data type of the compare() method's parameter to be Object, and hence you will not be able to compare the Student type(user-defined type) objects.

然后,默认情况下,假设compare()方法的参数的数据类型为Object,因此您将无法比较Student类型(用户定义类型)的对象。

时间为例! (Time for an Example!)

Student class:

学生班:

class Student
int roll;
  String name;
  Student(int r,String n)
  {
      roll = r;
      name = n;
  }
  public String toString()
  {
      return roll+" "+name;
  }

MyComparator class:

MyComparator类:

This class defines the comparison logic for Student class based on their roll. Student object will be sorted in ascending order of their roll.

此类根据学生的学习成绩为其定义了比较逻辑。 学生对象将按其卷升序排列。

class MyComparator implements Comparator<Student>
{
  public int compare(Student s1,Student s2)
    {
        if(s1.roll == s2.roll) return 0;
        else if(s1.roll > s2.roll) return 1;
        else return -1;
    }
}

Now let's create a Test class with main() function,

现在让我们使用main()函数创建一个Test类,

public class Test
{

   public static void main(String[] args)
   {
       TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());
       ts.add(new Student(45, "Rahul"));
       ts.add(new Student(11, "Adam"));
       ts.add(new Student(19, "Alex"));
       System.out.println(ts);
   }

}

[ 11 Adam, 19 Alex, 45 Rahul ]

[11亚当,亚历克斯19,拉胡尔45]

As you can see in the ouput Student object are stored in ascending order of their roll.

正如您在输出中看到的那样,Student对象按其升序存储。

Note:

注意:

  • When we are sorting elements in a collection using Comparator interface, we need to pass the class object that implements Comparator interface.

    当使用Comparator接口对集合中的元素进行排序时,我们需要传递实现Comparator接口的类对象。

  • To sort a TreeSet collection, this object needs to be passed in the constructor of TreeSet.

    要对TreeSet集合进行排序,需要在TreeSet的构造函数中传递此对象。

  • If any other collection, like ArrayList,was used, then we need to call sort method of Collections class and pass the name of the collection and this object as a parameter.

    如果使用了其他任何集合(如ArrayList),则需要调用Collections类的sort方法,并将集合名称和该对象作为参数传递。

  • For example, If the above program used ArrayList collection, the public class test would be as follows:

    例如,如果上述程序使用ArrayList集合,则公共类测试将如下所示:

public class Test
{
   public static void main(String[] args)
   {
       ArrayList< Student> ts = new ArrayList< Student>();
       ts.add(new Student(45, "Rahul"));
       ts.add(new Student(11, "Adam"));
       ts.add(new Student(19, "Alex"));
       Collections.sort(ts,new MyComparator()); /*passing the name of the ArrayList and the
object of the class that implements Comparator in a predefined sort() method in Collections
class*/
       System.out.println(ts);
   }
}

翻译自: https://www.studytonight.com/java/comparators-interface-in-java.php

java集合比较器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,Comparator是一个接口,它定义了一个用于比较两个对象的方法compare(Object o1, Object o2)。Comparator接口通常用于对集合中的元素进行排序。 Comparator接口中的compare方法返回一个int值,表示两个对象的相对顺序。如果第一个对象小于第二个对象,则返回负数;如果第一个对象等于第二个对象,则返回0;如果第一个对象大于第二个对象,则返回正数。 Comparator接口的实现类可以使用匿名内部类、Lambda表达式或单独的类来创建。在比较两个对象时,可以使用任何属性或方法来定义它们之间的关系。 下面是一个使用Comparator接口对字符串进行排序的例子: ``` List<String> strings = Arrays.asList("apple", "orange", "banana", "pear"); Collections.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { return s1.compareTo(s2); } }); ``` 这个例子中,我们创建了一个字符串列表,并使用Collections.sort方法将其排序。我们使用了一个匿名内部类来实现Comparator接口,将字符串按字典序排序。 在Java中,比较器的顺序是根据返回值来确定的。如果compare方法返回负数,则第一个对象在第二个对象之前;如果compare方法返回正数,则第一个对象在第二个对象之后;如果compare方法返回0,则两个对象相等,它们的相对位置不变。 比较器的实现通常需要考虑到多个因素,例如按照价格排序时可能需要同时考虑产品的名称、品牌、型号等因素。在这种情况下,我们可以使用Java 8中引入的多字段排序方法,或者创建一个自定义比较器来实现排序。 总之,Comparator是Java中非常重要的一个接口,它提供了一种灵活的方法来对集合中的对象进行排序。熟练掌握Comparator接口的使用方法可以让我们更好地处理集合数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值