JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to sort an array using comparator?


Description:

Java Arrays class provides few utility methods. One of the utility method Arrays.sort() helps us to sort an Array of objects by passing Comparator object, where Comparator holds the sorting logic. Below example shows how to sort an array using Comparator.


Code:
package com.java2novice.arrays;

import java.util.Arrays;
import java.util.Comparator;

public class MyStringArraySorting {

	public static void main(String a[]){
		
		String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
		Arrays.sort(strArr,new Comparator<String>(){

			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}});
		
		for(String str:strArr){
			System.out.println(str);
		}
	}
}

Output:
C++
JAVA
PERL
PLAY
STRUTS
<< Previous Program 
Knowledge Centre
Transient and Volatile Modifiers
Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized.

Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
Famous Quotations
Millions long for immortality who do not know what to do with themselves on a rainy Sunday afternoon.
-- Susan Erz

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.