Home Tutorial Java Core Arrange strings according to their length

 
 

Share on Google+Share on Google+
Arrange strings according to their length
Posted on: August 2, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to arrange the strings according to their length in ascending order.

Arrange strings according to their length

In this section, you will learn how to arrange the strings according to their length in ascending order. For this, user is allowed to enter three strings according to their choice. The method comapare() of Comparator interface compare the length of all the strings. All these strings are then stored into the list. Then the Collections.sort() method sort the list of strings according to their length.

Here is the code:

import java.util.*;

class Arrange implements Comparator {
	public int compare(String o1, String o2) {
		if (o1.length() > o2.length()) {
			return 1;
		} else if (o1.length() < o2.length()) {
			return -1;
		} else {
			return 0;
		}
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter First String: ");
		String st1 = input.nextLine();

		System.out.print("Enter Second String: ");
		String st2 = input.nextLine();

		System.out.print("Enter Third String: ");
		String st3 = input.nextLine();
		List list = new ArrayList();
		list.add(st1);
		list.add(st2);
		list.add(st3);
		Collections.sort(list, new Arrange());
		System.out.print(list.get(0) + " " + list.get(1) + " " + list.get(2));

	}
}

Output:

Enter First String: Welcome
Enter Second String: To
Enter Third String: Roseindia
To Welcome Roseindia
Advertisement

Related Tags for Arrange strings according to their length:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 2, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com