Java 集合实例


完整代码中包含以下所有的集合操作


数组转集合、集合转数组
集合比较
HashMap遍历
集合长度
集合打乱顺序
集合遍历
集合反转
删除集合中指定元素
只读集合
集合输出
List 循环移动元素
查找 List 中的最大最小值
遍历 HashTable 的键值
使用 Enumeration 遍历HashTable
List 截取


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args) {
        int n = 5; // 5个元素
        String[] name = new String[n];
        for (int i = 0; i < n; i++) {
            name[i] = String.valueOf(i);
        }
        // 使用 Java Util 类的 Arrays.asList(name) 方法将数组转换为集合
        List<String> list = Arrays.asList(name);
        System.out.println(list); // 输出集合
        // 使用 Java Util 类的 list.toArray() 方法将集合转为数组
        String[] name1 = list.toArray(new String[0]);
        for (int i = 0; i < name1.length; i++)
            System.out.println(name1[i]); // 输出数组

        // for循环输出集合元素
        // for (String li : list) {
        // String str = li;
        // System.out.print(str + " ");
        // }

        String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
        Set<String> set = new TreeSet<String>();
        // 将字符串转换为集合
        for (int i = 0; i < coins.length; i++) {
            set.add(coins[i]);
        }
        System.out.println(set);
        // 使用 Collection 类的 Collection.min() 和 Collection.max() 来比较集合中的元素
        System.out.println(Collections.min(set));
        System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
        System.out.println(Collections.max(set));
        System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));

        // 使用 Collection 类的 iterator() 方法来遍历集合
        HashMap<String, String> hMap = new HashMap<String, String>();
        hMap.put("1", "1st");
        hMap.put("2", "2nd");
        hMap.put("3", "3rd");
        Collection<String> cl = hMap.values();
        Iterator<String> itr = cl.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }

        // 使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序
        List<Integer> list1 = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
            list1.add(new Integer(i));
        System.out.println("打乱前:");
        System.out.println(list1);

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

        // List集合的遍历
        listTest();

        // Set集合的遍历
        setTest();

        // 集合反转
        String[] a = { "A", "B", "C" };
        revTest(a);

        // 删除集合中指定元素
        remTest();

        // 只读集合
        unmTest();

        // 集合输出
        outTest();

        // List 循环移动元素
        List<String> rot = Arrays.asList("one Two three Four five six".split(" "));
        System.out.println("List :" + rot);
        Collections.rotate(rot, 3); // 使用 Collections 类的 rotate() 来循环移动元素,方法第二个参数指定了移动的起始位置
        System.out.println("rotate: " + rot);

        // 查找 List 中的最大最小值
        System.out.println("最大值: " + Collections.max(rot));
        System.out.println("最小值: " + Collections.min(rot));

        // 遍历 HashTable 的键值
        Hashtable<String, String> ht = new Hashtable<String, String>();
        ht.put("1", "One");
        ht.put("2", "Two");
        ht.put("3", "Three");
        Enumeration<String> k = ht.keys(); // 使用 Hashtable 类的 keys() 方法来遍历输出键值
        while (k.hasMoreElements()) {
            System.out.println(k.nextElement());
        }
        // 使用 Enumeration 遍历 HashTable
        Enumeration<String> e = ht.elements();
        while (e.hasMoreElements()) {
            System.out.println(e.nextElement());
        }

        // 集合中添加不同类型元素
        addTest();

        // List 元素替换
        List<String> rep = Arrays.asList("one Two three Four five six one three Four".split(" "));
        System.out.println("List :" + rep);
        Collections.replaceAll(rep, "one", "hundrea");
        System.out.println("replaceAll: " + rep);

        // List 截取
        List<String> sub = Arrays.asList("one Two three Four five six one three Four".split(" "));
        System.out.println("List :" + sub);
        List<String> sublist = Arrays.asList("three Four".split(" "));
        System.out.println("子列表 :" + sublist);
        System.out.println("indexOfSubList: " + Collections.indexOfSubList(sub, sublist));
        System.out.println("lastIndexOfSubList: " + Collections.lastIndexOfSubList(sub, sublist));
    }

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

        // 使用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("a");
        list.add("b");

        // 使用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);
        }
    }

    // 使用 Collection 和 Listiterator 类的 listIterator() 和 collection.reverse()
    // 方法来反转集合中的元素
    private static void revTest(String[] a) {
        List<String> l = new ArrayList<String>();
        for (int i = 0; i < a.length; i++) {
            l.add(a[i]);
        }
        ListIterator<String> 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());
    }

    // 使用 Collection 类的 collection.remove() 方法来删除集合中的指定的元素
    private static void remTest() {
        System.out.println("集合实例!\n");
        int size;
        HashSet<String> collection = new HashSet<String>();
        String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
        Iterator<String> 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");
    }

    // 使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读
    private static void unmTest() {
        List<String> stuff = Arrays.asList(new String[] { "a", "b" });
        List<String> list = new ArrayList<String>(stuff);
        list = Collections.unmodifiableList(list);
        try {
            list.set(0, "new value"); // 抛出异常,无法添加
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        }
        Set<String> set = new HashSet<String>(stuff);
        set = Collections.unmodifiableSet(set);
        Map<?, ?> map = new HashMap<Object, Object>();
        map = Collections.unmodifiableMap(map);
        System.out.println("集合现在是只读");
    }

    // 使用 Java Util 类的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法将集合元素输出
    private static void outTest() {
        System.out.println("TreeMap 实例!\n");
        TreeMap<Integer, String> tMap = new TreeMap<Integer, String>();
        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());
    }

    private static void addTest() {
        List<String> lnkLst = new LinkedList<String>();
        lnkLst.add("element1");
        lnkLst.add("element2");
        lnkLst.add("element3");
        displayAll(lnkLst);
        List<String> aryLst = new ArrayList<String>();
        aryLst.add("x");
        aryLst.add("y");
        aryLst.add("z");
        displayAll(aryLst);
        Set<String> hashSet = new HashSet<String>();
        hashSet.add("set1");
        hashSet.add("set2");
        hashSet.add("set3");
        displayAll(hashSet);
        SortedSet<String> treeSet = new TreeSet<String>();
        treeSet.add("1");
        treeSet.add("2");
        treeSet.add("3");
        displayAll(treeSet);
        LinkedHashSet<String> lnkHashset = new LinkedHashSet<String>();
        lnkHashset.add("one");
        lnkHashset.add("two");
        lnkHashset.add("three");
        displayAll(lnkHashset);
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("key1", "J");
        map1.put("key2", "K");
        map1.put("key3", "L");
        displayAll(map1.keySet());
        displayAll(map1.values());
        SortedMap<String, String> map2 = new TreeMap<String, String>();
        map2.put("key1", "JJ");
        map2.put("key2", "KK");
        map2.put("key3", "LL");
        displayAll(map2.keySet());
        displayAll(map2.values());
        LinkedHashMap<String, String> map3 = new LinkedHashMap<String, String>();
        map3.put("key1", "JJJ");
        map3.put("key2", "KKK");
        map3.put("key3", "LLL");
        displayAll(map3.keySet());
        displayAll(map3.values());
    }

    private static void displayAll(Collection<String> col) {
        Iterator<String> itr = col.iterator();
        while (itr.hasNext()) {
            String str = (String) itr.next();
            System.out.print(str + " ");
        }
        System.out.println();
    }
}

猜你喜欢

转载自blog.csdn.net/shu_ze/article/details/80486933