Java Tutorial/Collections/Collections Sort

Материал из Java эксперт
Перейти к: навигация, поиск

Keeping upper and lowercase letters together

import java.util.Arrays;
import java.util.ruparator;
public class MainClass {
  public static void main(String[] args) {
    String[] sa = new String[] { "adf", "fdsa", "ASDF", "FSA", "r", "R" };
    System.out.println("Before sorting: " + Arrays.asList(sa));
    Arrays.sort(sa, new AlphabeticComparator());
    System.out.println("After sorting: " + Arrays.asList(sa));
  }
}
class AlphabeticComparator implements Comparator {
  public int compare(Object o1, Object o2) {
    String s1 = (String) o1;
    String s2 = (String) o2;
    return s1.toLowerCase().rupareTo(s2.toLowerCase());
  }
}
/**/



Before sorting: [adf, fdsa, ASDF, FSA, r, R]
After sorting: [adf, ASDF, fdsa, FSA, r, R]


Reversing Order

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainClass {
  public static void main(String[] a) {
    List list = new ArrayList();
    list.add("A");
    list.add("C");
    list.add("B");
    Collections.sort(list, Collections.reverseOrder());
    System.out.println(list);
  }
}



[C, B, A]


Sorting a Collection containing user defined Objects

import java.util.Arrays;
class Person implements Comparable<Person> {
  public Person(String firstName, String surname) {
    this.firstName = firstName;
    this.surname = surname;
  }
  public String toString() {
    return firstName + " " + surname;
  }
  public int compareTo(Person person) {
    int result = surname.rupareTo(person.surname);
    return result == 0 ? firstName.rupareTo(((Person) person).firstName) : result;
  }
  private String firstName;
  private String surname;
}
public class MainClass {
  public static void main(String[] args) {
    Person[] authors = { new Person("A", "B"), 
                         new Person("C", "D"),
                         new Person("E", "F"), 
                         new Person("Z", "Y"),
                         new Person("X", "T"), 
                         new Person("O", "R") };
    Arrays.sort(authors);
    System.out.println("\nThe cast is ascending sequence is:\n");
    for (Person person : authors) {
      System.out.println(person);
    }
  }
}



The cast is ascending sequence is:
  A B
  C D
  E F
  O R
  X T
  Z Y


Sorting a List

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    List list = Arrays.asList("a","c","b");
    Collections.sort(list);
    for (int i = 0, n = list.size(); i < n; i++) {
      if (i != 0)
        System.out.print(", ");
      System.out.print(list.get(i));
    }
    System.out.println();
  }
}



a, b, c