List/Set/Map集合排序/有序集合

‍‍其中 Set表明無序、不可重複的集合; List表明有序、重複的集合; ‍Map則表明具備映射關係的集合。 Queue體系集合表明一種隊列集合實現。‍‍java

使用Collections.sort對List集合排序

Collections.sort的兩種重載形式算法

public static <T extends Comparable<? super T>> void sort(List<T> list) {
}
public static <T> void sort(List<T> list, Comparator<? super T> c) {
}

People.javaide

package sort;

public class People implements Comparable<People> {

    public int age;
    public String name;

    public People(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    /**
     * 這個方法定義排序的規則
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(People o) {
        return this.age - o.getAge();
    }

    @Override
    public String toString() {
        return "People{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

Student.java性能

package sort;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-9-10
 * Time: 下午10:39
 * To change this template use File | Settings | File Templates.
 */
public class Student {

    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Teacher.java測試

package sort;

import java.util.Comparator;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-9-10
 * Time: 下午11:24
 * To change this template use File | Settings | File Templates.
 */
public class Teacher implements Comparator<Teacher> {

    public int age;

    public Teacher() {
    }

    public Teacher(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compare(Teacher o1, Teacher o2) {
        return o1.getAge() - o2.getAge();
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "age=" + age +
                '}';
    }
}

排序的測試:this

package sort;

import org.junit.Test;

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

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-9-10
 * Time: 下午10:32
 * To change this template use File | Settings | File Templates.
 */
public class SortTest {
    /**
     * 排序List<String>  升序排序
     * 排序規則是String類的compareTo
     */
    @Test
    public void test() {
        //sort方法的第一種使用方法
        List<String> list1 = new ArrayList<String>();
        list1.add("b");
        list1.add("a");
        list1.add("c");
        list1.add("e");
        list1.add("g");
        list1.add("j");
        list1.add("w");
        list1.add("b");
        Collections.sort(list1);    //默認的按升序排序
        for (String s : list1) {
            System.out.println(s);
        }
    }


    /**
     * 排序List<String>  降序排序
     * 排序規則是String類的compareTo
     */
    @Test
    public void test1212() {
        List<String> list1 = new ArrayList<String>();
        list1.add("b");
        list1.add("a");
        list1.add("c");
        list1.add("e");
        list1.add("g");
        list1.add("j");
        list1.add("w");
        list1.add("b");
        Collections.sort(list1, Collections.reverseOrder());
        for (String s : list1) {
            System.out.println(s);
        }
    }

    /**
     * 反轉元素的順序
     */
    @Test
    public void test7675() {
        List<String> list1 = new ArrayList<String>();
        list1.add("b");
        list1.add("a");
        list1.add("c");
        list1.add("e");
        list1.add("g");
        list1.add("j");
        list1.add("w");
        list1.add("b");
        Collections.reverse(list1);
        for (String s : list1) {
            System.out.println(s);
        }
    }


    /**
     * People類實現Comparable接口,實現compareTo方法。
     * 在compareTo方法中定義排序規則
     */
    @Test
    public void test89() {
        //sort的第二種使用方法
        List<People> peoples = new ArrayList<People>();
        peoples.add(new People(12, "lyx"));
        peoples.add(new People(13, "lyx"));
        peoples.add(new People(4, "lyx"));
        peoples.add(new People(1, "lyx"));
        Collections.sort(peoples);
        for (People p : peoples) {
            System.out.println(p.toString());
        }

    }

    /**
     * Teacher類實現Comparator接口,實現compare方法
     */
    @Test
    public void test86() {
        List<Teacher> teachers = new ArrayList<Teacher>();
        teachers.add(new Teacher(12));
        teachers.add(new Teacher(1));
        teachers.add(new Teacher(5));
        teachers.add(new Teacher(2));
        teachers.add(new Teacher(9));
        Collections.sort(teachers, new Teacher());
        for (Teacher t : teachers) {
            System.out.println(t.toString());
        }
    }


    /**
     * 在sort方法中,傳入Comparator接口的匿名對象,實現compare方法
     * 在compare方法中定義排序規則
     */
    @Test
    public void test80990() {
        //sort的第三種使用方法
        List<Student> students = new ArrayList<Student>();
        students.add(new Student("lyx", 12));
        students.add(new Student("lyx", 1));
        students.add(new Student("lyx", 7));
        students.add(new Student("lyx", 4));
        students.add(new Student("lyx", 3));

        //實現Comparator接口(使用匿名內部類實現Comparator接口)
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        for (Student s : students) {
            System.out.println(s.toString());
        }
    }
}

 

LinkedHashSet以元素插入順序遍歷元素

(1)HashSet是Set接口的實現。HashSet按Hash算法來存儲集合中的元素,具備很好的存取和查找性能。spa

(2)HashSet不能保證元素的排列順序,順序可能與添加順序不一樣,順序也有可能發生變化。code

(3)當向HashSet集合中存入一個元素時,HashSet會調用該對象的hashCode()方法來獲得該對象的hashCode值,而後根據該HashCode值決定該對象在HashSet中的存儲位置。若是有兩個元素經過equals()方法比較返回true,但它們的hashCode()方法返回值不相等,HashSet將會把它們存儲在不一樣的位置,依然能夠添加成功。即,HashSet集合判斷兩個元素相等的標準是兩個對象經過equals()方法比較相等,而且兩個對象的hashCode()方法返回值也相等。orm

LinkedHashSet集合也是根據元素的hashCode值來決定元素的存儲位置,但它同時使用鏈表維護元素的次序,這樣使得元素看起來是以插入的順序保存的。也就是說,當遍歷LinkedHashSet集合裏的元素時,LinkedHashSet將會按元素的添加順序來訪問集合裏的元素。對象

package sort;


import org.junit.Test;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-9-10
 * Time: 下午10:55
 * To change this template use File | Settings | File Templates.
 */
public class SortTest2 {


    /**
     * 測試LinkedHashSet
     * LinkedHashSet集合也是根據元素的hashCode值來決定元素的存儲位置,
     * 但它同時使用鏈表維護元素的次序,這樣使得元素看起來是以插入的順序保存的。
     */
    @Test
    public void test867() {
        Set<String> stringSet = new HashSet<String>();
        stringSet.add("aasdfasdf");
        stringSet.add("b");
        stringSet.add("c");
        stringSet.add("dddddd");
        stringSet.add("e");
        for (String s : stringSet) {
            System.out.println(s);
        }


        /**
         *  這是打印結果,能夠看到不是按照插入順序排列的
         *  b
         *  c
         *  dddddd
         *  aasdfasdf
         *  e
         */
        System.out.println();
        Set<String> set = new LinkedHashSet<String>();
        set.add("aasdfasdf");
        set.add("b");
        set.add("c");
        set.add("dddddd");
        set.add("e");
        for (String s : set) {
            System.out.println(s);
        }

        /**
         * 能夠看到LinkedHashSet是按插入順序遍歷的,
         * 要注意其保存順序仍是按照hashCode值來決定
         * aasdfasdf
         * b
         * c
         * dddddd
         * e
         */
    }
}

 

TreeSet使集合處於排序狀態

TreeSet是SortedSet接口的實現類,能夠確保集合元素處於排序狀態。

‍TreeSet須要額外的紅黑樹算法來維護集合元素的次序。只有當須要一個保持排序的Set時,才應該使用TreeSet,不然都應該使用HashSet。‍

TreeSet中的幾個方法:

  • Object first():返回集合中的第一個元素。

  • Object last():返回集合中的最後一個元素。

  • Object lower(Object e):返回集合中位於指定元素以前的元素(即小於指定元素的最大元素,參數元素不須要是TreeSet集合裏的元素)。

  • Object higher(Object e):返回集合中位於指定元素以後的元素(即大於指定元素的最小元素,參數元素不須要是TreeSet集合裏的元素)。

  • SortedSet subSet(formElement,toElement):返回次Set的子集合,範圍從formElement(包含)到toElement(不包含)。

  • SortedSet headSet(toElement):返回此Set的子集,由小於toElement的元素組成。

  • SortedSet tailSet(fromElement):返回此Set的子集,由大於或等於fromElement的元素組成。

下面貼代碼:

@Test
public void test323() {
    Set<People> peoples = new TreeSet<People>();
    peoples.add(new People(12, "lyx"));
    peoples.add(new People(13, "lyx"));
    peoples.add(new People(4, "lyx"));
    peoples.add(new People(1, "lyx"));
    for (People p : peoples) {
        System.out.println(p.toString());
    }
}

@Test
public void test80990() {
    //sort的第三種使用方法
    Set<Student> students = new TreeSet<Student>(new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    students.add(new Student("lyx", 12));
    students.add(new Student("lyx", 1));
    students.add(new Student("lyx", 7));
    students.add(new Student("lyx", 4));
    students.add(new Student("lyx", 3));

    for (Student s : students) {
        System.out.println(s.toString());
    }
}

 

LinkedHashMap以元素插入順序遍歷元素

LinkedHashMap是HashMap的子類,使用雙向鏈表來維護entry的插入次序,迭代輸出時,元素順序與插入順序一致。

/**
 * LinkedHashMap是HashMap的子類,使用雙向鏈表來維護entry的插入次序,迭代輸出時,元素順序與插入順序一致。
 */
@Test
public void test121() {
    Map<String, String> map0 = new HashMap<String, String>();
    map0.put("qwer", "value");
    map0.put("b", "value");
    map0.put("c", "value");
    map0.put("jklkjh", "value");
    map0.put("a", "value");

    Set<String> keySet = map0.keySet();
    for (String s : keySet) {
        System.out.println(s);
    }

    System.out.println();

    Map<String, String> map1 = new LinkedHashMap<String, String>();
    map1.put("qwer", "value");
    map1.put("b", "value");
    map1.put("c", "value");
    map1.put("jklkjh", "value");
    map1.put("a", "value");

    Set<String> keySet1 = map1.keySet();
    for (String s : keySet1) {
        System.out.println(s);
    }
}

打印結果:

a

b

c

qwer

jklkjh

 

qwer

b

c

jklkjh

a

 

TreeMap使集合處於排序狀態

TreeMap採用「紅黑樹」的排序二叉樹來保存Map中的每一個Entry。每一個Entry爲紅黑樹的一個節點。

全部的Entry老是根據key按指定的規則保持有序。紅黑樹是一種自平衡二叉樹,每一個節點的值都大於或等於它的左子樹中全部節點的值,都小於或等於它的右子樹中全部節點的值。

/**
 * 使用TreeMap使集合處於排序狀態
 */
@Test
public void test78728() {
    Map<Integer, String> map0 = new TreeMap<Integer, String>();
    map0.put(1, "value");
    map0.put(90, "value");
    map0.put(89, "value");
    map0.put(34, "value");
    map0.put(21, "value");
    map0.put(3, "value");
    Set<Integer> keySet1 = map0.keySet();
    for (Integer i : keySet1) {
        System.out.println(i);
    }
}


/**
 * TreeMap集合排序的對象必需要實現Comparable接口
 * 實現compareTo方法
 */
@Test
public void test898686() {
    Map<People, Integer> peopleIntegerMap = new TreeMap<People, Integer>();
    peopleIntegerMap.put(new People(12, "lyx"), 9876);
    peopleIntegerMap.put(new People(9, "lyx"), 9876);
    peopleIntegerMap.put(new People(2, "lyx"), 9876);
    peopleIntegerMap.put(new People(8, "lyx"), 9876);
    peopleIntegerMap.put(new People(7, "lyx"), 9876);
    peopleIntegerMap.put(new People(6, "lyx"), 9876);
    peopleIntegerMap.put(new People(5, "lyx"), 9876);

    Set<People> peopleSet = peopleIntegerMap.keySet();
    for (People people : peopleSet) {
        System.out.println(people.toString());
    }
}


/**
 * 實例化TreeMap時,傳入Comparator接口的匿名類對象
 * 實現compare方法,定義排序規則
 */
@Test
public void test7868() {
    Map<Student, Integer> studentIntegerMap = new TreeMap<Student, Integer>(new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    studentIntegerMap.put(new Student("lyx", 12), 7890);
    studentIntegerMap.put(new Student("lyx", 11), 7890);
    studentIntegerMap.put(new Student("lyx", 10), 7890);
    studentIntegerMap.put(new Student("lyx", 9), 7890);
    studentIntegerMap.put(new Student("lyx", 8), 7890);
    studentIntegerMap.put(new Student("lyx", 7), 7890);
    studentIntegerMap.put(new Student("lyx", 6), 7890);
    studentIntegerMap.put(new Student("lyx", 5), 7890);

    Set<Student> studentSet = studentIntegerMap.keySet();
    for (Student student : studentSet) {
        System.out.println(student.toString());
    }
}

==============END==============

相關文章
相關標籤/搜索