Home Tutorial Java Core Arrange strings according to their length

 
 

Arrange strings according to their length
Posted on: August 2, 2010 at 12:00 AM
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

Related Tags for Arrange strings according to their length:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.