trier string ordre alphabetique java 1/10/11/2 code example

Example 1: trier un tableau de string java

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Arrays;
 
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String[] data = new String[] {"Raaata", "Tatatara", "Ratatouille", "Gygyghhhygra", "Bla", "Toto"};
        Arrays.sort(data, new Comparator<String>() {
            public int compare(String s1, String s2) {
                int idx1 = s1.toLowerCase().indexOf("ra");
                int idx2 = s2.toLowerCase().indexOf("ra");
                if(idx1 == -1) {
                    idx1 = Integer.MAX_VALUE;
                }
                if(idx2 == -1) {
                    idx2 = Integer.MAX_VALUE;
                }
                Integer i1 = new Integer(idx1);
                Integer i2 = new Integer(idx2);
                return i1.compareTo(i2);
            }
        });
        System.out.println("Sorted array=" + Arrays.toString(data));
    }
}

Example 2: trier un tableau de string java

String[] names = {"John", "Steve", "Shane", "Adam", "Ben"};
System.out.println("String array before sorting : " + Arrays.toString(names));
Arrays.sort(names); 
System.out.println("String array after sorting in ascending order : " + Arrays.toString(names));

Example 3: trier par ordre alphabétique java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StringSorter {

	public static void main(String[] args) {
		List namesList = new ArrayList();
		namesList.add("Top language");
		namesList.add("Happy programming !");
		namesList.add("Java");
		namesList.add("HackTrack");
		Collections.sort(namesList);
		System.out.println(namesList);

Tags:

Java Example