How would I sort an array or arrayList of strings into alphabetical order?

Dani AI

Generated

For : use the JDK sort utilities rather than hand-rolling comparisons. already pointed to the standard array API and showed using a Comparator for objects; ' manual routine is a useful exercise but is usually slower and more error-prone than the built-in sorts. The examples below show concise, modern patterns (Java 8+) that cover the common needs: simple alphabetical, case-insensitive, locale-aware, and sorting by a String property on an object.

import java.util.*;
import java.text.Collator;
import java.util.Locale;

List<String> words = new ArrayList<>(Arrays.asList("apple","Banana","cherry","file2","file10"));

// 1) simple lexicographic (case-sensitive)
words.sort(Comparator.naturalOrder());

// 2) case-insensitive
words.sort(String.CASE_INSENSITIVE_ORDER);

// 3) locale-aware (handles language/accents)
Collator collator = Collator.getInstance(Locale.FRANCE);
collator.setStrength(Collator.PRIMARY); // treat base letters as equal (ignore accents)
words.sort(collator);

// 4) sort objects by username (preferred over a verbose Comparator class)
List<User> users = /* ... */;
users.sort(Comparator.comparing(User::getUsername));

Practical notes: sort a copy if the original order must be kept (new ArrayList<>(orig)). If strings contain embedded numbers and a human-friendly order is needed, implement or use a "natural" / alphanum comparator rather than plain lexicographic compare. Avoid calling toLowerCase() without a Locale for case-insensitive keys. Keep comparators consistent (consistency-with-equals matters for sorted sets/maps). In production code prefer the standard APIs for correctness, stability and speed; hand-rolled sorts are mostly for learning or special requirements.

Recommended Answers

All 3 Replies

How would I sort an array or arrayList of strings into alphabetical order?

You could do something like this--

import java.util.*;

public class Sort_Kit{

	private final static int NUMBERS = 10;
	private static int passes = 0;

	public static void main(String[] args){
		ArrayList<String> strings = new ArrayList<String>(0);
		Random rgen = new Random();

		for(int i = 0; i < NUMBERS; i++)
			strings.add("" + (rgen.nextInt(999)%10));

		System.out.println(strings);
		try{Sort_Kit.<String>sortArrayList(strings, true);}catch(Throwable t){}
		System.out.println(strings);
		System.out.println("Sorted in " + passes + " passes!");
	}

	static <T extends Comparable<T> > void sortArrayList(ArrayList<T> arg, boolean order) throws Exception{
		int turn = 0;
		while(!Sort_Kit.<T>isSorted(arg)){
			for(int i = 0; i < arg.size() - 1; i++){
				T temp = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1))),
				 temp2 = (order)
				? (arg.get(i).compareTo(arg.get(i + 1)) >  arg.get(i + 1).compareTo(arg.get(i))
				? (arg.get(i)) : (arg.get(i + 1)) ) : ((arg.get(i).compareTo(arg.get(i + 1)) <  arg.get(i + 1).compareTo(arg.get(i)) )
				? (arg.get(i)) : (arg.get(i + 1)));
				arg.set(i, temp);
				arg.set(i + 1, temp2);
				System.out.println(temp + "  " + temp2);
				Thread.sleep(250); // for debug purposes
			}
			System.out.println(arg);
			turn++;
		}
              passes = turn;
	}

	private static <T extends Comparable<T> > boolean isSorted(ArrayList<T> arg){
		int count = 0;
		for(int i = 0; i < arg.size() - 1; i++)
			count = (arg.get(i).compareTo(arg.get(i + 1)) <= arg.get(i + 1).compareTo(arg.get(i))) ? ++count: count;

		System.out.println(count);
		return count == (arg.size() - 1);
	}
}

The example uses numbers as Strings but you can use regular Strings as well.

Use the Arrays class: Arrays

Signature:
public static void sort(Object[] a)

String [] arr=new String[5];
//put stuff into the array.

Arrays.sort(arr);

The sort will take any array with Objects as long they implement the Comparable interface and they can be compared with each other.
The String object does implement the Comparable interface. It is better the array you use as input to have objects of the same type.

You can also sort integers:

A) as primitive types:

int [] arr=new int[5];
//put stuff into the array.

Arrays.sort(arr);

A) as objects:

Integer [] arr=new Integer[5];
//put stuff into the array.

Arrays.sort(arr);

The Integer object does implement the Comparable interface.

In case someone wants to sort an objects ArrayList using a criteria. In my case, I had User objects, and would like to sort it by username. The getUsername() method returns the username's String.

Where you want it to be sorted, supposing your ArrayList is named "users".

Collections.sort(users, new byUsername());

The comparator class

public class byUsername implements Comparator
{
    public int compare(Object o1, Object o2)
    {
        User u1 = (User) o1;
        User u2 = (User) o2;
        return u1.getUsername().compareTo(u2.getUsername());
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.