Java實(shí)例-集合

1、Java 實(shí)例 – 數(shù)組轉(zhuǎn)集合:使用 Java Util 類的 Arrays.asList(name) 方法將數(shù)組轉(zhuǎn)換為集合。

public class Collection_ArrayTo {

public Collection_ArrayTo()throws IOException {

int n =5;// 5 個(gè)元素

? ? ? ? String[] name =new String[n];

for(int i =0; i < n; i++){

name[i] = String.valueOf(i);

}

List list = Arrays.asList(name);

System.out.println("數(shù)組轉(zhuǎn)集合:");

for(String li: list){

String str = li;

System.out.print(str +" ");

}

}

}

執(zhí)行結(jié)果:

2、Java 實(shí)例 – 集合比較:將字符串轉(zhuǎn)換為集合并使用 Collection 類的 Collection.min() 和 Collection.max() 來比較集合中的元素。

public class Collection_Compare {

public Collection_Compare() {

String[] coins = {"Penny","nickel","dime","Quarter","dollar" };

Set set =new TreeSet();

for (int i =0; i < coins.length; i++) {

set.add(coins[i]);

}

System.out.println("ASCII最小:"+Collections.min(set));//按照ASCII值大小排序

? ? ? ? System.out.println("ASCII最?。ê雎源笮懀?+Collections.min(set, String.CASE_INSENSITIVE_ORDER));//忽略字母的大小寫

? ? ? ? System.out.println("````````````````````````");

System.out.println("ASCII最大:"+Collections.max(set));

System.out.println("ASCII最大(忽略大小寫):"+Collections.max(set, String.CASE_INSENSITIVE_ORDER));

}

}

執(zhí)行結(jié)果:

3、Java 實(shí)例 – HashMap遍歷:使用 Collection 類的 iterator() 方法來遍歷集合。

public class Collection_HashMap {//HashMap只遍歷鍵值

? ? public Collection_HashMap() {

HashMap< String, String> hMap =

new HashMap< String, String>();

hMap.put("1","1st");

hMap.put("2","2nd");

hMap.put("3","3rd");

Collection cl = hMap.values();

Iterator itr = cl.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

}

}

}

執(zhí)行結(jié)果:

4、Java 實(shí)例 – 集合長度:使用 Collections 類 的collection.add() 來添加數(shù)據(jù)并使用 collection.size()來計(jì)算集合的長度。

public class Collection_GetLength {

public Collection_GetLength() {

System.out.println("集合實(shí)例!\n" );

int size;

HashSet collection =new HashSet ();

String str1 ="Yellow", str2 ="White", str3 =

"Green", str4 ="Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("集合數(shù)據(jù): ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

size = collection.size();

if (collection.isEmpty()){

System.out.println("集合是空的");

}

else{

System.out.println("集合長度: " + size);

}

System.out.println();

}

}

執(zhí)行結(jié)果:

5、Java 實(shí)例 – 集合打亂順序:使用 Collections 類 Collections.shuffle() 方法來打亂集合元素的順序。

public class Collection_Disorganize {

public Collection_Disorganize() {

List list =new ArrayList();

for (int i =0; i <10; i++)

list.add(new Integer(i));

System.out.println("原集合:");

System.out.println(list);

for (int i =1; i <3; i++) {

System.out.println("第" + i +"次打亂:");

Collections.shuffle(list);

System.out.println(list);

}

}

}

執(zhí)行結(jié)果:

6、Java 實(shí)例 – 集合遍歷:遍歷從Collection接口延伸出的List、Set和以鍵值對形式作存儲(chǔ)的Map類型的集合,以下分別使用普通for,增強(qiáng)型的 for ,iterator 等方式來遍歷集合。

public class Collection_Ergodic {

public Collection_Ergodic() {

// List集合的遍歷

? ? ? ? listTest();

// Set集合的遍歷

? ? ? ? setTest();

}

private static void setTest() {

Set set =new HashSet();

set.add("JAVA");

set.add("C");

set.add("C++");

// 重復(fù)數(shù)據(jù)添加失敗

? ? ? ? set.add("JAVA");

set.add("JAVASCRIPT");

// 使用iterator遍歷set集合

? ? ? ? Iterator it = set.iterator();

System.out.println("\nSet集合迭代器遍歷:");

while (it.hasNext()) {

String value = it.next();

System.out.print(value+"? ");

}

// 使用增強(qiáng)for循環(huán)遍歷set集合

? ? ? ? System.out.println("\nSet集合增強(qiáng)for循環(huán)遍歷:");

for(String s: set){

System.out.print(s+"? ");

}

}

// 遍歷list集合

? ? private static void listTest() {

List list =new ArrayList();

list.add("A");

list.add("B");

list.add("C");

list.add("D");

// 使用iterator遍歷

? ? ? ? Iterator it = list.iterator();

System.out.println("List集合迭代器遍歷:");

while (it.hasNext()) {

String value = it.next();

System.out.print(value+"? ");

}

// 使用傳統(tǒng)for循環(huán)進(jìn)行遍歷

? ? ? ? System.out.println("\nList集合傳統(tǒng)for循環(huán)遍歷:");

for (int i =0, size = list.size(); i < size; i++) {

String value = list.get(i);

System.out.print(value+"? ");

}

// 使用增強(qiáng)for循環(huán)進(jìn)行遍歷

? ? ? ? System.out.println("\nList集合增強(qiáng)for循環(huán)遍歷:");

for (String value : list) {

System.out.print(value+"? ");

}

}

}

執(zhí)行結(jié)果:

7、Java 實(shí)例 – 集合反轉(zhuǎn):使用 Collection 和 Listiterator 類的 listIterator() 和 collection.reverse() 方法來反轉(zhuǎn)集合中的元素。

public class Collection_Reverse {

public Collection_Reverse() {

String[] coins = {"A","B","C","D","E" };

List l =new ArrayList();

for (int i =0; i < coins.length; i++)

l.add(coins[i]);

ListIterator liter = l.listIterator();

System.out.println("反轉(zhuǎn)前");

while (liter.hasNext())

System.out.print(liter.next()+"? ");

Collections.reverse(l);

liter = l.listIterator();

System.out.println("\n反轉(zhuǎn)后");

while (liter.hasNext())

System.out.print(liter.next()+"? ");

}

}

執(zhí)行結(jié)果:

8、Java 實(shí)例 – 刪除集合中指定元素:使用 Collection 類的 collection.remove() 方法來刪除集合中的指定的元素。

public class Collection_Delete {

public Collection_Delete() {

System.out.println("集合實(shí)例!\n" );

int size;

HashSet collection =new HashSet ();

String str1 ="Yellow", str2 ="White", str3 =

"Green", str4 ="Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("集合數(shù)據(jù): ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

collection.remove(str2);

System.out.println("刪除 [" + str2 +"]\n");

System.out.print("當(dāng)前集合的數(shù)據(jù)是: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() +" ");

}

System.out.println();

size = collection.size();

System.out.println("集合大小: " + size +"\n");

}

}

執(zhí)行結(jié)果:

9、Java 實(shí)例 – 只讀集合:使用 Collection 類的 Collections.unmodifiableList() 方法來設(shè)置集合為只讀。

public class Collection_OnlyRead {

public Collection_OnlyRead()throws Exception {

List stuff = Arrays.asList(new String[] {"a","b" });

List list =new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

list.set(0,"new value");

}

catch (UnsupportedOperationException e) {

}

Set set =new HashSet(stuff);

set = Collections.unmodifiableSet(set);

Map map =new HashMap();

map = Collections.unmodifiableMap(map);

System.out.println("只讀集合");

}

}

執(zhí)行結(jié)果:

10、Java 實(shí)例 – 集合輸出:使用 Java Util 類的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法將集合元素輸出。

public class Collection_Print {

public Collection_Print() {

TreeMap tMap =new TreeMap();

tMap.put(1,"Sunday");

tMap.put(2,"Monday");

tMap.put(3,"Tuesday");

tMap.put(4,"Wednesday");

tMap.put(5,"Thursday");

tMap.put(6,"Friday");

tMap.put(7,"Saturday");

System.out.println("TreeMap 鍵:"

? ? ? ? ? ? ? ? + tMap.keySet());

System.out.println("TreeMap 值:"

? ? ? ? ? ? ? ? + tMap.values());

System.out.println("鍵為 5 的值為: " + tMap.get(5));

System.out.println("第一個(gè)鍵: " + tMap.firstKey()

+" Value: "

? ? ? ? ? ? ? ? + tMap.get(tMap.firstKey()));

System.out.println("最后一個(gè)鍵: " + tMap.lastKey()

+" Value: "+ tMap.get(tMap.lastKey()));

System.out.println("移除第一個(gè)數(shù)據(jù): "

? ? ? ? ? ? ? ? + tMap.remove(tMap.firstKey()));

System.out.println("現(xiàn)在 TreeMap 鍵為: "

? ? ? ? ? ? ? ? + tMap.keySet());

System.out.println("現(xiàn)在 TreeMap 包含: "

? ? ? ? ? ? ? ? + tMap.values());

System.out.println("移除最后一個(gè)數(shù)據(jù): "

? ? ? ? ? ? ? ? + tMap.remove(tMap.lastKey()));

System.out.println("現(xiàn)在 TreeMap 鍵為: "

? ? ? ? ? ? ? ? + tMap.keySet());

System.out.println("現(xiàn)在 TreeMap 包含: "

? ? ? ? ? ? ? ? + tMap.values());

}

}

執(zhí)行結(jié)果:

11、Java 實(shí)例 – 集合轉(zhuǎn)數(shù)組:Java Util 類的 list.add() 和 list.toArray() 方法將集合轉(zhuǎn)為數(shù)組。

public class Collection_ToArray {

public Collection_ToArray(){

List list =new ArrayList();

list.add("A");

list.add("B");

list.add("C");

list.add("D");

String[] s1 = list.toArray(new String[0]);

for(int i =0; i < s1.length; ++i){

String contents = s1[i];

System.out.print(contents+"? ");

}

}

}

執(zhí)行結(jié)果:

12、Java 實(shí)例 – List 循環(huán)移動(dòng)元素:使用 Collections 類的 rotate() 來循環(huán)移動(dòng)元素,方法第二個(gè)參數(shù)指定了移動(dòng)的起始位置。

public class Collection_Rotate {

public Collection_Rotate() {

List list = Arrays.asList("one Two three Four five six".split(" "));

System.out.println("List :"+list);

Collections.rotate(list,3);

System.out.println("rotate: " + list);

}

}

執(zhí)行結(jié)果:

13、Java 實(shí)例 – 查找 List 中的最大最小值:使用 Collections 類的 max() 和 min() 方法來獲取List中最大最小值。

public class Collection_ListMaxMin {

public Collection_ListMaxMin() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println(list);

System.out.println("最大值: " + Collections.max(list));

System.out.println("最小值: " + Collections.min(list));

}

}

執(zhí)行結(jié)果:

14、Java 實(shí)例 – 遍歷 HashTable 的鍵值:使用 Hashtable 類的 keys() 方法來遍歷輸出鍵值。

public class Collection_HashTableKeys {

public Collection_HashTableKeys() {

Hashtable ht =new Hashtable();

ht.put("1","One");

ht.put("2","Two");

ht.put("3","Three");

Enumeration e = ht.keys();

System.out.println("HashTable的鍵值:");

while (e.hasMoreElements()){

System.out.println(e.nextElement());

}

}

}

執(zhí)行結(jié)果:

15、Java 實(shí)例 – 集合中添加不同類型元素:

public class Collection_Add {

public Collection_Add() {

List lnkLst =new LinkedList();

lnkLst.add("element1");

lnkLst.add("element2");

lnkLst.add("element3");

lnkLst.add("element4");

displayAll(lnkLst);

List aryLst =new ArrayList();

aryLst.add("x");

aryLst.add("y");

aryLst.add("z");

aryLst.add("w");

displayAll(aryLst);

Set hashSet =new HashSet();

hashSet.add("set1");

hashSet.add("set2");

hashSet.add("set3");

hashSet.add("set4");

displayAll(hashSet);

SortedSet treeSet =new TreeSet();

treeSet.add("1");

treeSet.add("2");

treeSet.add("3");

treeSet.add("4");

displayAll(treeSet);

LinkedHashSet lnkHashset =new LinkedHashSet();

lnkHashset.add("one");

lnkHashset.add("two");

lnkHashset.add("three");

lnkHashset.add("four");

displayAll(lnkHashset);

Map map1 =new HashMap();

map1.put("key1","J");

map1.put("key2","K");

map1.put("key3","L");

map1.put("key4","M");

displayAll(map1.keySet());

displayAll(map1.values());

SortedMap map2 =new TreeMap();

map2.put("key1","JJ");

map2.put("key2","KK");

map2.put("key3","LL");

map2.put("key4","MM");

displayAll(map2.keySet());

displayAll(map2.values());

LinkedHashMap map3 =new LinkedHashMap();

map3.put("key1","JJJ");

map3.put("key2","KKK");

map3.put("key3","LLL");

map3.put("key4","MMM");

displayAll(map3.keySet());

displayAll(map3.values());

}

static void displayAll(Collection col) {

Iterator itr = col.iterator();

while (itr.hasNext()) {

String str = (String) itr.next();

System.out.print(str +" ");

}

System.out.println();

}

}

執(zhí)行結(jié)果:

16、Java 實(shí)例 – List 元素替換:使用 Collections 類的 replaceAll() 來替換List中所有的指定元素。

public class Collection_Replace {

public Collection_Replace() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println("List :"+list);

Collections.replaceAll(list,"one","hundred");

System.out.println("one替換成hundred: " + list);

}

}

執(zhí)行結(jié)果:

17、Java 實(shí)例 – List 截?。?/b>使用 Collections 類的 indexOfSubList() 和 lastIndexOfSubList() 方法來查看子列表是否在列表中,并查看子列表在列表中所在的位置。

public class Collection_Cut {

public Collection_Cut() {

List list = Arrays.asList("one Two three Four five six one three Four".split(" "));

System.out.println("List :"+list);

List sublist = Arrays.asList("three Four".split(" "));

System.out.println("子列表 :"+sublist);

System.out.println("indexOfSubList: "

? ? ? ? ? ? ? ? + Collections.indexOfSubList(list, sublist));

System.out.println("lastIndexOfSubList: "

? ? ? ? ? ? ? ? + Collections.lastIndexOfSubList(list, sublist));

}

}

執(zhí)行結(jié)果:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、為什么會(huì)出現(xiàn)集合類 1.集合是一個(gè)容器,為了方便的對多個(gè)對象進(jìn)行操作。 2.集合容器同數(shù)組容器的...
    大禹編程扛把子閱讀 671評論 0 0
  • 轉(zhuǎn)載自:Java集合框架實(shí)例 1- 介紹 集合是程序和語言的基本思想。應(yīng)用程序通常都會(huì)應(yīng)用到集合,例如雇員的信息,...
    01_小小魚_01閱讀 478評論 0 1
  • 第十天 權(quán)限修飾符 public protected default private 同一類 true true ...
    炙冰閱讀 607評論 0 1
  • Collection ├List │├LinkedList │├ArrayList │└Vector │└Stac...
    AndyZX閱讀 961評論 0 1
  • 一、基礎(chǔ)知識(shí):1、JVM、JRE和JDK的區(qū)別:JVM(Java Virtual Machine):java虛擬機(jī)...
    殺小賊閱讀 2,563評論 0 4

友情鏈接更多精彩內(nèi)容