`

java Comparator Example

    博客分类:
  • Java
 
阅读更多

http://www.javadeveloper.co.in/java-example/java-comparator-example.html

Submitted by Andr on Tue, 10/26/2010 - 20:12
Java Examples
package examples;

/*
Java Comparator example.
This Java Comparator example describes how java.util.Comparator
interface is implemented to compare Java custom class objects.

This Java Comparator is passed to Collection's sorting method
(for example Collections.sort method) to perform sorting of Java custom
class objects.

*/

import java.util.*;

/*
java.util.Comparator interface declares two methods,
1) public int compare(Object object1, Object object2) and
2) boolean equals(Object object)
*/

/*
We will compare objects of the Employee class using custom comparators
on the basis of employee age and name.
*/

class Employee{
   
    private int age;   
    private String name;
   
    public void setAge(int age){
        this.age=age;   
    }
   
    public int getAge(){
        return this.age;   
    }
   
    public void setName(String name){
        this.name=name;   
    }
   
    public String getName(){   
        return this.name;   
    }
}

/*
User defined Java comparator.
To create custom java comparator, implement Comparator interface and
define compare method.

The below given comparator compares employees on the basis of their age.
*/

class AgeComparator implements Comparator{
   
    public int compare(Object emp1, Object emp2){
   
        /*
         * parameter are of type Object, so we have to downcast it
         * to Employee objects
         */
      
        int emp1Age = ((Employee)emp1).getAge();       
        int emp2Age = ((Employee)emp2).getAge();
      
        if(emp1Age > emp2Age)
            return 1;
        else if(emp1Age < emp2Age)
            return -1;
        else
            return 0;   
    }
   
}

/*
The below given comparator compares employees on the basis of their name.
*/

class NameComparator implements Comparator{

    public int compare(Object emp1, Object emp2){   

        //parameter are of type Object, so we have to downcast it to Employee objects
      
        String emp1Name = ((Employee)emp1).getName();       
        String emp2Name = ((Employee)emp2).getName();
      
        //uses compareTo method of String class to compare names of the employee
        return emp1Name.compareTo(emp2Name);
   
    }

}

/*
This Java comparator example compares employees on the basis of
their age and name and sort them in that order.
*/

public class JavaComparatorExample{
   
    public static void main(String args[]){
      
        //Employee array which will hold employees
        Employee employee[] = new Employee[2];
      
        //set different attributes of the individual employee.
        employee[0] = new Employee();
        employee[0].setAge(40);
        employee[0].setName("Joe");
      
        employee[1] = new Employee();
        employee[1].setAge(20);
        employee[1].setName("Mark");
      
        System.out.println("Order of employee before sorting is");
        //print array as is.
        for(int i=0; i < employee.length; i++){
            System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
        }
      
        /*
        Sort method of the Arrays class sorts the given array.       
        Signature of the sort method is,       
        static void sort(Object[] object, Comparator comparator)
      
        IMPORTANT: All methods defined by Arrays class are static. Arrays class       
        serves as a utility class.
        */
      
        //Sorting array on the basis of employee age by passing AgeComparator
        Arrays.sort(employee, new AgeComparator());
        System.out.println("\n\nOrder of employee after sorting by employee age is");
      
        for(int i=0; i < employee.length; i++){
            System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
        }
      
        //Sorting array on the basis of employee Name by passing NameComparator
        Arrays.sort(employee, new NameComparator());
      
        System.out.println("\n\nOrder of employee after sorting by employee name is");   
        for(int i=0; i < employee.length; i++){
            System.out.println( "Employee " + (i+1) + " name :: " + employee[i].getName() + ", Age :: " + employee[i].getAge());
        }
   
    }

}

/*
OUTPUT of the above given Java Comparable Example would be :
Order of employee before sorting is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
Order of employee after sorting by employee age is
Employee 1 name :: Mark, Age :: 20
Employee 2 name :: Joe, Age :: 40
Order of employee after sorting by employee name is
Employee 1 name :: Joe, Age :: 40
Employee 2 name :: Mark, Age :: 20
*/
分享到:
评论

相关推荐

    java8集合源码-Java8Example:Java8示例

    Comparator() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); Java 8 Collections.sort(names, (s1, s2) -&gt; s1.compareTo(s2)); #Java 8 - Lambda 表达式 句法 parameter ...

    JAVAAPI文档

    10. **示例(Example)**:尽管API文档主要关注接口和类的定义,但也可能包含简单的示例代码,展示如何使用特定的类或方法。 通过阅读和理解Java API文档,开发者可以更有效地编写代码,避免重复发明轮子,并且能够...

    HBASE-comparator.zip

    &lt;comparator class="com.example.NumericComparator" /&gt; ``` 请注意,这只是一个基础示例,实际应用中可能需要处理更复杂的情况,比如负数、浮点数、精度问题等。此外,自定义Comparator还需要考虑性能优化,因为...

    java8-example

    在这个"java8-example"项目中,我们可以深入学习和实践Java 8的核心特性。以下是一些主要的知识点: 1. **lambda表达式**: Java 8引入了lambda表达式,它是一种简洁的匿名函数表示方式。通过lambda,你可以将函数...

    高手总结Java初学者学习经验笔记整理

    public class Example { public static void main(String[] args) { ArrayList&lt;String&gt; list = new ArrayList(); list.add("Hello"); list.add("World"); for (String item : list) { System.out.println...

    Java笔记word.docx

    在比较列表中的元素大小时,可以使用`Collections.sort()`方法对列表进行排序,也可以通过`Comparator`接口自定义比较逻辑。 **示例**: ```java List&lt;Integer&gt; list = Arrays.asList(3, 1, 4, 1, 5); Collections...

    Advanced-Java-Programming-by-Example:示例高级Java编程

    在Java编程领域,"Advanced Java Programming by Example" 是一个深入探讨高级Java特性的主题,它涵盖了通用类、通用接口和通用方法等核心概念。这些概念是Java编程中的关键要素,对于提升代码的可复用性、灵活性和...

    java sort排序算法实例完整代码

    public class SortExample { public static void main(String[] args) { // 对基本类型数组进行排序 int[] numbers = {5, 3, 8, 1, 9}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); ...

    struts2 sort实例

    Comparator接口在Java中用于比较对象的顺序,我们需要实现它的`compare()`方法,该方法接收两个对象作为参数,并返回一个整数值,表示这两个对象的相对顺序。例如,如果我们想要根据某个字段(如名称、日期等)对...

    java-collection-example

    "java-collection-example"项目旨在展示如何使用Java Collections库的各种组件,包括接口、类和算法。这个库使得开发者能够高效地管理和操作对象集合,无论是简单的数组列表还是复杂的映射结构。 在Java中,集合...

    Java常用开源库(附源码地址).docx

    .sorted(Comparator.comparingInt(Widget::getWeight)) .mapToInt(Widget::getWeight) .sum(); ``` 这个例子中,我们从`widgets`列表中筛选出颜色为红色的Widget,按重量排序,然后计算所有符合条件的Widget的总...

    Javajdk5学习笔记

    Java JDK 5是Java开发工具包的一个重要版本,...在"example"这个文件中,可能包含了这些概念的实例代码和解释,对于初学者来说,通过阅读这些代码和笔记,能够更好地理解和掌握Java JDK 5的新特性,从而提升编程技能。

    Using_Java_Queue.zip_java队列

    - **PriorityQueue**:优先级队列,元素根据其自然顺序或Comparator排序。 - **LinkedBlockingQueue**:无界线程安全队列,基于链接节点实现,适合构建工作队列。 ### 5. 应用场景 队列在许多实际问题中都有应用,...

    java练习题

    ### Java练习题知识点详解 #### 1. 冒泡排序法 **知识点**: 冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到...

    java知识点总结

    - **对集合的排序**:可以通过实现Comparable接口来实现自然排序,或者通过Comparator接口来实现定制排序。 ##### 2.3 泛型 (GENERIC) - **泛型**:允许在类、接口和方法中使用类型参数,从而实现代码复用和类型...

    Java企业面试题整理及答案

    如果要在集合框架中实现比较功能,需要实现 `Comparable` 接口或使用 `Comparator` 接口。前者适用于自身类型间的比较,后者适用于不同类型的比较。 **15. 用插入法进行排序代码如下** 插入排序是一种简单的排序...

    java.数据结构.md

    Java集合框架还提供了迭代器(Iterator)、比较器(Comparator)等高级功能,让数据结构的使用更加灵活多样。 了解和掌握不同数据结构及其特性,能够帮助开发者在面对各种编程挑战时,快速选择合适的数据结构,从而...

    详解Java的闭包

    例如,`java.util.Comparator` 接口有一个默认方法 `thenComparing(Comparator&lt;? super T&gt; other)`,允许用户方便地组合多个比较条件。默认方法与 Lambda 表达式配合使用,可以创建更复杂的函数式编程模式。 总结来...

    SCJP Sun® Certified Programmer for Java™ 6 Study Guide chapter 7

    ### SCJP Sun® Certified Programmer for Java™ 6 Study Guide Chapter 7: Generics and Collections #### 认证目标概述 本章重点介绍了Java中的泛型(Generics)和集合(Collections),并着重于如何在实际编程...

    version-comparator:Android版本名称比较器库

    - **比较操作**:提供`compareTo`方法,可以比较两个版本字符串的大小,返回值遵循Java的比较原则,0表示相等,负数表示第一个版本小于第二个,正数表示大于。 - **排序功能**:可以对版本列表进行排序,确保它们...

Global site tag (gtag.js) - Google Analytics