栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java集合的方法有哪些(集合 java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java集合的方法有哪些(集合 java)

前言:

回顾Java基础部分中集合的一些常用操作。JDK的版本为1.8,使用单元测试运行程序。

1.Collection接口的常用方法:

package com.yan.collection;

import org.junit.Test;

import java.util.*;


public class CollectionTest {
    
    @Test
    public void test() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Jerry", 20));
        
        boolean contains = coll.contains(123);
        System.out.println(contains); //true
        System.out.println(coll.contains(new String("Tom"))); //true
        
        Collection coll1 = Arrays.asList(123, 45678);
        System.out.println(coll.containsAll(coll1)); //false
        //3.remove(Object obj):从当前集合中移除obj元素
        coll.remove(123);
        System.out.println(coll);
        //4.removeAll(Collection coll2):差集:从当前集合中移除coll2中所有的元素
        Collection coll2 = Arrays.asList(456, false);
        coll.removeAll(coll2);
        System.out.println(coll);
        //5.retainAll():交集:获取当前集合和coll3的交集,并返回给当前集合
        Collection coll3 = Arrays.asList(new String("Tom"));
        coll.retainAll(coll3);
        System.out.println(coll);

    }

    @Test
    public void test1() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Jerry", 20));
        //6.hashCode()返回当前对象的哈希值
        System.out.println(coll.hashCode());
        //7.集合-->数组:toArray()
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        //8.数组-->集合:调用Arrays类的静态方法asList()
        List list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);

        List arr1 = Arrays.asList(new int[]{1, 2, 3}); //视作一个元素
        System.out.println(arr1.size()); //1个元素

        List arr2 = Arrays.asList(new Integer[]{1, 2, 3}); //视作三个元素
        System.out.println(arr2.size()); //3个元素

        //9.iterator():返回Iterator接口的实例,用于遍历集合元素.
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()) {
            //iterator.next():取出迭代器的元素
            //iterator.hasNext():判断是否还有元素
            System.out.println(iterator.next());
        }
    }


    @Test
    public void test2() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Jerry", 20));
        //remove():删除集合中“Tom”
        
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if ("Tom".equals(obj)) {
                iterator.remove();
            }
        }
        //遍历集合方式一
        iterator = coll.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        //遍历集合方式二,同时也可以遍历数组
        //for(集合元素的类型 局部遍历 :集合对象)
        for(Object o :coll){
            System.out.println(o);
        }
    }

}

2.List接口的常用方法:

package com.yan.collection;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ListTest {
     
    @Test
    public void test(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add(new String("Tom"));
        list.add("AS");
        list.add(new Person("Jerry",19));
        System.out.println(list);
        //1. void add(int index, Object ele):在index位置插入ele元素
        list.add(1,"BE");
        System.out.println(list);
        //2. Boolean addAll(int index, Collection ele):从index位置开始将ele中所有元素添加进来
        List arr = Arrays.asList(1, 2, 3);
        list.addAll(arr);
        System.out.println(list.size()); //9
        //3. object get(int index):获取指定index位置的元素
        System.out.println(list.get(0));
        //4. int indexOf(Object obj):返回obj在集合中首次出现的位置,如不存在,则返回-1
        int index = list.indexOf(456);
        System.out.println(index);
        //5. int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
        System.out.println(list.lastIndexOf("AS"));
        //6. Object remove(int index):移除指定index位置的元素,并返回此元素
        Object remove = list.remove(0);
        System.out.println(remove);
        System.out.println(list);
        //7. Object set(int index, Object ele):设置指定index位置的元素ele
        list.set(1,"CS");
        System.out.println(list);
        //8. List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
        List subList = list.subList(2, 4);
        System.out.println(subList);
    }

    

}

3.Set接口的常用方法:

package com.yan.collection;

import org.junit.Test;

import java.util.*;


public class SetList {
    
    @Test
    public void test(){
        Set set = new HashSet();
        set.add(123);
        set.add(456);
        set.add(789);
        set.add("AA");
        set.add("BB");
        set.add(new Person("Tom",18));
        set.add(new Person("Jack",19));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    
    public void test1(){
        TreeSet set = new TreeSet();
        //向TreeSet中添加数据,要求是相同类的对象。
//        set.add(923);
//        set.add(456);
//        set.add(789);
//
//        Iterator iterator = set.iterator();
//        while (iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
        set.add(new Person("Tom",14));
        set.add(new Person("Jack",18));
        set.add(new Person("Shawn",19));
        set.add(new Person("Nie",16));
        set.add(new Person("Nie",20));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test2(){
        Comparator com = new Comparator() {
            //按照年龄从小到大排序
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Person && o2 instanceof Person){
                    Person person1 = (Person) o1;
                    Person person2 = (Person) o2;
                    return Integer.compare(person1.getAge(), person2.getAge());
                }else{
                    throw new RuntimeException("输入的数据类型不匹配");
                }
            }
        };

        TreeSet set1 = new TreeSet(com);

        set1.add(new Person("Tom",14));
        set1.add(new Person("Jack",18));
        set1.add(new Person("Shawn",19));
        set1.add(new Person("Nie",16));
        set1.add(new Person("Nie",20));

        Iterator iterator = set1.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

4.Map接口的常用方法:

package com.yan.collection;

import org.junit.Test;

import java.util.*;




public class MapTest {
    
    @Test
    public void test(){
        HashMap map = new HashMap();
        map.put("AA",123);
        map.put(789,234);
        map.put("CC",391);
        System.out.println(map); // {AA=123, CC=391, 789=234}

        HashMap map1 = new HashMap();
        map1.put("DD",563);
        map1.put("EE",189);
        map.putAll(map1);
        System.out.println(map); // {AA=123, CC=391, DD=563, EE=189, 789=234}

        Object value = map.remove("CC");
        System.out.println("删除的元素的值: "+value); // 391
        System.out.println(map); // {AA=123, DD=563, EE=189, 789=234}

        map.clear();
        System.out.println(map.size()); // 0
    }

    
    @Test
    public void test1(){
        HashMap map = new HashMap();
        map.put("AA",123);
        map.put(789,234);
        map.put("CC",391);
        System.out.println(map.get("AA")); //123

        boolean isExist = map.containsKey("CC");
        System.out.println(isExist); //true

        boolean value = map.containsValue(123);
        System.out.println(value); //true

        map.clear();

        System.out.println(map.isEmpty()); //true

    }

    
    @Test
    public void test2(){
        HashMap map = new HashMap();
        map.put("AA",123);
        map.put(789,234);
        map.put("CC",391);
        //遍历所有的key
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println();
        //遍历所有的value
        Collection values = map.values();
        for (Object o:values){
            System.out.println(o);
        }
        System.out.println();
        //遍历所有的key-value对
        //方式一:entrySet()
        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object o = iterator1.next();
            //entrySet集合中的元素都是entry
            Map.Entry entry = (Map.Entry) o;
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
        System.out.println();
        //方式二:通过key来遍历所有的键值对
        Set setKey = map.keySet();
        Iterator iterator2 = setKey.iterator();
        while (iterator2.hasNext()){
            Object key = iterator2.next();
            Object value = map.get(key);
            System.out.println(key+"---"+value);
        }

    
    }

    
    @Test
    //自然排序,其排序方法已经在Person类里重写,按姓名从大到小排序
    public void test3(){
        TreeMap map = new TreeMap();
        Person p1 = new Person("Tom",18);
        Person p2 = new Person("Shawn",19);
        Person p3 = new Person("Jerry",17);
        Person p4 = new Person("Caroline",16);

        map.put(p1,96);
        map.put(p2,98);
        map.put(p3,97);
        map.put(p4,93);

        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object o = iterator1.next();
            //entrySet集合中的元素都是entry
            Map.Entry entry = (Map.Entry) o;
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

    @Test
    //定制排序
    public void test4(){
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Person && o2 instanceof Person){
                    Person per1 = (Person) o1;
                    Person per2 = (Person) o2;
                    //按年龄从小到大
                    return Integer.compare(per1.getAge(),per2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });

        Person p1 = new Person("Tom",18);
        Person p2 = new Person("Shawn",19);
        Person p3 = new Person("Jerry",17);
        Person p4 = new Person("Caroline",16);

        map.put(p1,96);
        map.put(p2,98);
        map.put(p3,97);
        map.put(p4,93);

        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object o = iterator1.next();
            //entrySet集合中的元素都是entry
            Map.Entry entry = (Map.Entry) o;
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }


}

5.Collections工具类的使用:

package com.yan.collection;

import org.junit.Test;

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



public class CollectionsTest {
    @Test
    public void test(){
        
        List list = new ArrayList();
        list.add(123);
        list.add(34);
        list.add(63);
        list.add(8763);
        list.add(8763);
        list.add(8763);
        list.add(8763);
        list.add(10);
        System.out.println(list);
        //Collections.shuffle(list);
        //Collections.sort(list);
        //Collections.swap(list, 1, 2);
        //System.out.println(list);
        int frequency = Collections.frequency(list,8763);
        System.out.println(frequency);
    }

    @Test
    public void test1(){
        List list = new ArrayList();
        list.add(123);
        list.add(34);
        list.add(63);
        list.add(8763);
        //报异常: IndexOutOfBoundsException: Source does not fit in dest
//        List dest = new ArrayList();
//        Collections.copy(dest, list);
        //正确的写法:
        List dest = Arrays.asList(new Object[list.size()]);
        Collections.copy(dest, list);
        System.out.println(dest); //[123, 34, 63, 8763]

        
        //返回的list1即是线程安全的List
        List list1 = Collections.synchronizedList(list);
    }
}
 

6.集合举例使用的Person类:

package com.yan.collection;

import java.util.Objects;


public class Person implements Comparable{
    private String name;
    private int age;

    public Person() {
    }

    public Person(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 "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    //按照姓名从大到小排序,年龄从小到大
    public int compareTo(Object o) {
        if(o instanceof Person){
            Person person = (Person) o;
            int compare = -this.name.compareTo(person.name);
            if(compare!=0){
                return compare;
            }else {
                return Integer.compare(this.age, person.age);
            }
        }else{
            throw new RuntimeException("输入的类型不匹配");
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号