JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label collection. Show all posts
Showing posts with label collection. Show all posts

Comparator in java collection with example

3:50 AM
Comparator: When you want to sort the list of objects of a class,you can use Comparator interface. You don’t need to implement Comparator on the class whose objects need to be sorted. You can create a separate class and implement a Comparator interface as below. For example: 1 2 3 4 5 6 7 8 9 10 11 12 13   package com . arpit . java2blog ;   import java . util . Comparator ;   public class EmployeeSortByIdComparator implements Comparator {   @ Override public int compare ( Employee e1 , Employee e2 ) { return e1 . getEmpId ( ) - e2 . getEmpId ( ) ; } }   You can use different sorting logic based on different attributes of object that needs to be sorted. For example: Let’s say you want to sort list of employees by name,you can use below ocde to do that. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2

.