Java集合算法:列表排序、反轉、隨機排序、搜索列表元素之學習筆記

部分內容引用自:https://www.w3cschool.cn/java/java-collections-algorithms.html


package com.hqy.String;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JavaJiheAlgorithm {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
     
   /*
              一.Collection類中的兩個靜態方法會對List進行排序。
            1.sort(List list)按照由元素實現的Comparable接口定義的順序對List中的元素進行排序。
            2.sort(List list,Comparator c)使用傳入的Comparator對象對元素進行排序。 
    */
		
	List<String> list=new ArrayList<>();
	list.add("f");
	list.add("edf");
	list.add("y");
	list.add("c");
	
	System.out.println("List:"+list);
	Collections.sort(list);
	System.out.println("Sorted List:"+list);
	
	/*
	 * 二.使用List接口中的sort()方法按其元素長度的升序對列表進行排序:
	 */
	list.add("oedr");
	list.sort(Comparator.comparing(String::length));
	System.out.println("Sorted list:"+list);
		
	
	/*
	 三.搜索列表
	   Collections類中的兩個靜態binarySearch()方法在List中搜索鍵。
                              該方法使用二分搜索算法執行搜索。
     注意:     1.List 必須按升序排序,然後才能使用 binarySearch()方法。
               2. 如果在列表中找到該鍵,則該方法將在列表中返回其索引。          
	       3.如果在列表中沒有找到鍵,它返回( - (insertion_index)-1),
	                 其中 Math.abs(( - (insertion_index)-1))是我們可以插入這個鍵的索引仍然保持列表訂購。
               4.在列表中找不到鍵時,返回值爲負值。
     */
	Collections.sort(list);
	int index=Collections.binarySearch(list, "f");
	System.out.println("f in list is at:"+index);
	
	index=Collections.binarySearch(list, "go on");
	System.out.println("go on in list is at:"+index);
	
	
	
	/*
	 四.隨機播放列表
	       Collections類的shuffle()方法
	 */
	
	Collections.shuffle(list);
	System.out.println(list);
	
	Collections.shuffle(list);
	System.out.println(list);
	
	
	/*
	 五.反向列表:使用 Collections 類的 reverse()的靜態方法來反轉列表中的元素。
	 */
	Collections.sort(list);
	System.out.println(list);
	Collections.reverse(list);
	System.out.println("reverse:"+list);
	}

}

結果:

List:[f, edf, y, c]
Sorted List:[c, edf, f, y]
Sorted list:[c, f, y, edf, oedr]
f in list is at:2
go on in list is at:-4
[y, edf, f, c, oedr]
[edf, c, y, oedr, f]
[c, edf, f, oedr, y]
reverse:[y, oedr, f, edf, c]



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章