实例-Java集合

数组转集合
import java.util.*;
import java.io.*;

public class ArrayToCollection{
   public static void main(String args[]) 
   throws IOException{
      int n = 5;         // 5 个元素
      String[] name = new String[n];
      for(int i = 0; i < n; i++){
         name[i] = String.valueOf(i);
      }
      List<String> list = Arrays.asList(name); 
      System.out.println();
      for(String li: list){
         String str = li;
         System.out.print(str + " ");
      }
   }
}

结果:

0 1 2 3 4

集合比较
import java.util.Collections; 
import java.util.Set;
import java.util.TreeSet;

class Main {
   public static void main(String[] args) {
      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(Collections.min(set));
      System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
      for(int i=0;i<=10;i++)
         System.out.print("-");
      System.out.println("");
      System.out.println(Collections.max(set));
      System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));
   }
}

结果:

Penny
dime
-----------
nickel
Quarter

HashMap遍历
import java.util.*;

import java.util.*;

public class Main {
   public static void main(String[] args) {
      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());
     }
   }
}

结果:

3rd
2nd
1st

集合长度
import java.util.*;

public class Main {
   public static void main(String [] args) {   
      System.out.println( "集合实例!\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("集合数据: ");  
      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();
   }
}

结果:

集合实例!

集合数据: White Yellow Blue Green 
集合长度: 4

集合打乱顺序
import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            list.add(new Integer(i));
        System.out.println("打乱前:");
        System.out.println(list);

        for (int i = 1; i < 6; i++) {
            System.out.println("第" + i + "次打乱:");
            Collections.shuffle(list);
            System.out.println(list);
        }
    }
}

结果:

打乱前:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第1次打乱:
[2, 0, 5, 1, 4, 9, 7, 6, 3, 8]
第2次打乱:
[2, 6, 4, 8, 5, 7, 9, 1, 0, 3]
第3次打乱:
[6, 5, 1, 0, 3, 7, 2, 4, 9, 8]
第4次打乱:
[1, 3, 8, 4, 7, 2, 0, 6, 5, 9]
第5次打乱:
[3, 0, 7, 9, 5, 8, 4, 2, 1, 6]

集合遍历
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Main {

   public static void main(String[] args) {
      // List集合的遍历
      listTest();
      // Set集合的遍历
      setTest();
   }

   private static void setTest() {
      Set<String> set = new HashSet<String>();
      set.add("JAVA");
      set.add("C");
      set.add("C++");
      // 重复数据添加失败
      set.add("JAVA");
      set.add("JAVASCRIPT");

      // 使用iterator遍历set集合
      Iterator<String> it = set.iterator();
      while (it.hasNext()) {
         String value = it.next();
         System.out.println(value);
      }

      // 使用增强for循环遍历set集合
      for(String s: set){
         System.out.println(s);
      }
   }

   // 遍历list集合
   private static void listTest() {
      List<String> list = new ArrayList<String>();
      list.add("菜");
      list.add("鸟");
      list.add("教");
      list.add("程");
      list.add("www.w3cschool.cc");

      // 使用iterator遍历
      Iterator<String> it = list.iterator();
      while (it.hasNext()) {
         String value = it.next();
         System.out.println(value);
      }

      // 使用传统for循环进行遍历
      for (int i = 0, size = list.size(); i < size; i++) {
         String value = list.get(i);
         System.out.println(value);
      }

      // 使用增强for循环进行遍历
      for (String value : list) {
         System.out.println(value);
      }
   }
}

结果:

菜
鸟
教
程
www.w3cschool.cc
菜
鸟
教
程
www.w3cschool.cc
菜
鸟
教
程
www.w3cschool.cc
JAVA
JAVASCRIPT
C++
C
JAVA
JAVASCRIPT
C++
C

关于Map类型集合的遍历
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

//增强For循环
public class Main {

   public static void main(String[] args) {
      // 创建一个HashMap对象,并加入了一些键值对。
      Map<String, String> maps = new HashMap<String, String>();
      maps.put("1", "PHP");
      maps.put("2", "Java");
      maps.put("3", "C");
      maps.put("4", "C++");
      maps.put("5", "HTML");

      // 传统的遍历map集合的方法1; keySet()
      //traditionalMethod1(maps);
      // 传统的遍历map集合的方法2; entrySet()
      //traditionalMethod2(maps);
      // 使用增强For循环来遍历map集合方法1; keySet()
      //strongForMethod1(maps);
      // 使用增强For循环来遍历map集合方法2; entrySet()
      strongForMethod2(maps);
   }

   private static void strongForMethod2(Map<String, String> maps) {
      Set<Entry<String, String>> set = maps.entrySet();
      for (Entry<String, String> entry : set) {
         String key = entry.getKey();
         String value = entry.getValue();
         System.out.println(key + " : " + value);
      }
   }

   private static void strongForMethod1(Map<String, String> maps) {
      Set<String> set = maps.keySet();
      for (String s : set) {
         String key = s;
         String value = maps.get(s);
         System.out.println(key + " : " + value);
      }
   }

   // 使用entrySet()方法,获取maps集合中的每一个键值对,
   private static void traditionalMethod2(Map<String, String> maps) {
      Set<Map.Entry<String, String>> sets = maps.entrySet();
      // 取得迭代器遍历出对应的值。
      Iterator<Entry<String, String>> it = sets.iterator();
      while (it.hasNext()) {
         Map.Entry<String, String> entry = (Entry<String, String>) it.next();
         String key = entry.getKey();
         String value = entry.getValue();
         System.out.println(key + " : " + value);
      }
   }

   // 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。
   private static void traditionalMethod1(Map<String, String> maps) {
      Set<String> sets = maps.keySet();
      // 取得迭代器遍历出对应的值
      Iterator<String> it = sets.iterator();
      while (it.hasNext()) {
         String key = it.next();
         String value = maps.get(key);
         System.out.println(key + " : " + value);
      }
   }
}

结果:

1 : PHP
2 : Java
3 : C
4 : C++
5 : HTML

集合反转
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

class Main {
   public static void main(String[] args) {
      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("反转前");
      while (liter.hasNext())
         System.out.println(liter.next());
      Collections.reverse(l);
      liter = l.listIterator();
      System.out.println("反转后");
      while (liter.hasNext())
         System.out.println(liter.next());
   }
}

结果:

反转前
A
B
C
D
E
反转后
E
D
C
B
A

删除集合中指定元素
import java.util.*;

public class Main {
   public static void main(String [] args) {   
      System.out.println( "集合实例!\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("集合数据: ");  
      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("现在集合的数据是: ");
      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      System.out.println("集合大小: " + size + "\n");
   }
}

结果:

集合实例!

集合数据: White Yellow Blue Green 
删除之后 [White]

现在集合的数据是: Yellow Blue Green 
集合大小: 3

只读集合
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {
   public static void main(String[] argv) 
   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("集合现在是只读");
   }
}

结果:

集合现在是只读

集合输出
import java.util.*;

public class Main{
   public static void main(String[] args) {
      System.out.println("TreeMap 实例!\n");
      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)+ "\n");
      System.out.println("第一个键: " + tMap.firstKey() 
      + " Value: " 
      + tMap.get(tMap.firstKey()) + "\n");
      System.out.println("最后一个键: " + tMap.lastKey() 
      + " Value: "+ tMap.get(tMap.lastKey()) + "\n");
      System.out.println("移除第一个数据: " 
      + tMap.remove(tMap.firstKey()));
      System.out.println("现在 TreeMap 键为: " 
      + tMap.keySet());
      System.out.println("现在 TreeMap 包含: " 
      + tMap.values() + "\n");
      System.out.println("移除最后一个数据: " 
      + tMap.remove(tMap.lastKey()));
      System.out.println("现在 TreeMap 键为: " 
      + tMap.keySet());
      System.out.println("现在 TreeMap 包含: " 
      + tMap.values());
   }
}

结果:

TreeMap 实例!

TreeMap 键:[1, 2, 3, 4, 5, 6, 7]
TreeMap 值:[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
键为 5 的值为: Thursday

第一个键: 1 Value: Sunday

最后一个键: 7 Value: Saturday

移除第一个数据: Sunday
现在 TreeMap 键为: [2, 3, 4, 5, 6, 7]
现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

移除最后一个数据: Saturday
现在 TreeMap 键为: [2, 3, 4, 5, 6]
现在 TreeMap 包含: [Monday, Tuesday, Wednesday, Thursday, Friday]

集合转数组
import java.util.*;

public class Main{
   public static void main(String[] args){
      List<String> list = new ArrayList<String>();
      list.add("菜"); 
      list.add("鸟"); 
      list.add("教");
      list.add("程");
      list.add("www.w3cschool.cc");
      String[] s1 = list.toArray(new String[0]); 
      for(int i = 0; i < s1.length; ++i){
         String contents = s1[i];
         System.out.print(contents);
     } 
   }
}

结果:

菜鸟教程www.w3cschool.cc

List 循环移动元素
import java.util.*;

public class Main {
   public static void main(String[] args) {
      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);
   }
}

结果:

List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]

查找 List 中的最大最小值

import java.util.*;

public class Main {
   public static void main(String[] args) {
      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));
   }
}

结果:

[one, Two, three, Four, five, six, one, three, Four]
最大值: three
最小值: Four

遍历 HashTable 的键值
import java.util.Enumeration;
import java.util.Hashtable;

public class Main {
   public static void main(String[] args) {
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.keys();
      while (e.hasMoreElements()){
         System.out.println(e.nextElement());
      }
   }
}

结果:

3
2
1

使用 Enumeration 遍历 HashTable
import java.util.Enumeration;
import java.util.Hashtable;

public class Main {
   public static void main(String[] args) {
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.elements();
      while(e.hasMoreElements()){
         System.out.println(e.nextElement());
      }
   }
}

结果:

Three
Two
One

集合中添加不同类型元素
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;


public class Main {
   public static void main(String[] args) {
      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();
   }
}

结果:

element1 element2 element3 element4 
x y z w 
set3 set2 set4 set1 
1 2 3 4 
one two three four 
key1 key2 key3 key4 
J K L M 
key1 key2 key3 key4 
JJ KK LL MM 
key1 key2 key3 key4 
JJJ KKK LLL MMM 

List 元素替换
import java.util.*;

public class Main {
   public static void main(String[] args) {
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      Collections.replaceAll(list, "one", "hundread");
      System.out.println("replaceAll: " + list);
   }
}

结果:

List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]

List 截取
import java.util.*;

public class Main {
   public static void main(String[] args) {
      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));
   }
}

结果:

List :[one, Two, three, Four, five, six, one, three, Four]
子列表 :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值