集合(Collection集合,Map集合,Collections工具类)

1.Collection

Collection集合共性方法

        Collection<String> collection =new ArrayList<>();
        collection.add("a");//添加,返回Boolean,添加成功返回true
        collection.remove("a");//删除,返回Boolean,删除成功返回true
        collection.clear();//清空集合
        boolean contains = collection.contains("a");//是否包含“a”这个字符串
        boolean empty = collection.isEmpty();//判断是否为空
        int size = collection.size();//集合长度size;数组长度length
        Object[] objects = collection.toArray();//集合转换数组

1.1 List(有序,有索引,允许重复元素)

常用方法一: 包含带索引方法(特有的方法)
 .add()//指定位置添加
 .get()//获取指定位置元素
 .remove()//指定位置移除
 .set()//指定位置替换
常用方法二: list集合3种遍历方式
        //普通for循环
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println(s);
        }
        //迭代器
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String s= iterator.next();
            System.out.println(s);
        }
        //增强for循环
        for (String s : list) {
            System.out.println(s);
        }
常用方法三: 两个List集合取交集
//两个集合取交集
List<String> list1 = new ArrayList<>();
//省略 往list中添加的过程......
List<String> list2 = new ArrayList<>();
//省略 往list中添加的过程......
list1.retainAll(list2);
常用方法四: List集合拼接成String( 自定义自定义分割符 )
//这个要注意List中要是String类型,否则会出现 类转换异常
List<String> list = new ArrayList<>();
//省略 往list中添加字符串的过程......

// 方式一,可以用stream流
String s= list.stream().collect(Collectors.joining("#"));

// 方式二,String.join()方法
String s= String.join(",", list);
常用方法五: 字符串转换为List
String str = "a,b,c";
List<String> list = Arrays.asList(str.split(","));//这个Arrays.asList()得到的list长度是不可改变的,当添加和删除元素时会抛异常UnsupportedOperationException
//如果需要对这个list添加删除等,还需要把这个集合遍历一下,存入到ArrayList中

1.1.1 ArrayList(底层数组,查询快,增删慢,多线程)

//多态创建集合对象
List list= new ArrayList();

1.1.2 LinkedList(底层链表,查询慢,增删快,多线程)

//注意:使用LinkedList特有方法,不能使用多态创建对象了
LinkedList linkedList = new LinkedList();

操作首位元素方法(特有的)

//首尾位置 添加
addFirst() <=> push()/ addLast()
//首尾位置 获取
getFirst() / getLast()
//首尾位置 获取
removeFirst()<=>pop() / removeLast()

1.1.3 Vector(底层数组,单线程,1.0版本最早期集合,现在几乎不用了)

1.2 Set(无索引,不包含重复元素)

不能使用普通for循环

set集合存储不重复元素:
前提 : 存储的元素重写hashCode()和equals()方法。
原理 : 在调用add()方法时会先调用hashCode()方法比较地址中是否有这个哈希值,没有–>存储,有(哈希冲突)–>调用再调用euqals()方法比较是否是相同元素,不相同就存,相同就不存

1.2.1 HashSet (哈希表结构,查询速度快,无序)

如果用HashSet 存储自定义类型数据,一定要重写hashCode()和equals()方法,才能保证HashSet集合的去重的特性.

Set set = new HashSet();

1.2.2 LinkedHashSet(继承了HashSet,哈希表+链表结构 , 有序)

链表结构是记录元素的存储顺序的,保证了集合的有序

2.Map

Map中的key必须重写hashCode()方法和equals()方法才能保证key的唯一性。

常用方法

//添加
map.put(key,value);//如果key重复了,会出现value值覆盖

//查找
map.get(key);

//删除
map.remove(key);// key存在返回值是value,key不存在放回null

//是否包含指定的key
boolean b = map.containsKey(key);

2.2.1 HashMap(数组+单项链表/哈希表结构, 无序, 多线程, 可有一个null键)

结构:
1.8之前 数组+单项链表 结构
1.8之后 数组+单项链表/红黑树(链表长度超过8之后变成红黑树) 结构

自定义类作为键值

		//自定义类作为vlaue
        Map<String,Student> map = new HashMap<>();
        //自定义类作为key
        Map<Student,String> map = new HashMap<>();

Map集合的遍历方式(Map集合无法直接遍历)

		//方法一: keySet()
        Map<String,Object> map = new HashMap<>();
        //省略map中添加值....
        Set<String> stringSet = map.keySet();//map中所有的key存到set集合中
        //迭代器遍历,也可以通过增强for遍历
        Iterator<String> iterator = stringSet.iterator();//遍历获取每一个key
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = map.get(key);//通过key 获取value值
            System.out.println(value);
        }


		//方法二: entrySet()
		Map<String, Object> map = new HashMap<>();
        //省略map中添加值....
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();//map中所有的entry对象(键值对对象)存到set集合中
        for (Map.Entry<String, Object> entry : entrySet) {
            String key = entry.getKey();//获取key
            Object value = entry.getValue();//获取value
            System.out.println(key+"和"+value);
        }

2.2.2 LinkedHashMap(继承HashMap,哈希表+链表结构,有序)

LinkedHashMap linkedHashMap = new LinkedHashMap();

2.2.3 Hashtable(几乎不用了,被HashMap取代了)

1.0版本的双列集合,底层是哈希表结构,单线程(线程安全的)
Hashtable键和值都不允许为null

2.2.4 Properties(Hashtable集合子类,唯一一个和IO流相结合的集合)

属性集合:
特点:
1.存储属性名和属性值
2.属性名和属性值都是字符串类型
3.没有泛型
4.和流有关

        /****************基本方法****************/
        //创建集合
        Properties properties = new Properties();
        //添加属性
        properties.setProperty("username","张三");
        properties.setProperty("password","123456");
        //获取value
        String val = properties.getProperty("username");
        //遍历方法一: keySet 和 entrySet都可以
        //遍历方法二: stringPropertyNames 遍历出属性名的set集合
        Set<String> keyNames = properties.stringPropertyNames();

        /****************和流有关的方法****************/

        //1.list方法
        //创建打印流
        PrintWriter pw = new PrintWriter(new File("d:\\aaa.txt"));
        //list方法打印
        properties.list(pw);
        pw.close();

        //2.store方法
        //字节输出流  一般这属性用properties扩展名
        FileOutputStream fos = new FileOutputStream(new File("d:\\bbb.properties"));
        //保存方法
        properties.store(fos,"随便写个注释");
        fos.close();

        //3.load方法
        FileInputStream fis = new FileInputStream(new File("d:\\bbb.properties"));
        //加载
        properties.load(fis);
        fis.close();
        System.out.println(properties);

2.2.5 TreeMap

3.Collections(集合工具类)

3.1、Collections.addAll()往集合中添加所有元素

        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list,"a","b","c","d","e");//往集合中添加所有元素
        System.out.println(list);

3.2、Collections.shuffle()随机打乱集合顺序

        ArrayList<String> list = new ArrayList<>();
        Collections.shuffle(list);//随机打乱集合顺序(每次执行集中的元素顺序都不一样)
        System.out.println(list);

3.3、Collections.sort(list)将集合中元素排序(默认升序),参数只能穿list集合

		//Integer排序:
        ArrayList<Integer> list = new ArrayList<>();
        Collections.addAll(list,17,3,14,6,10);//往集合中添加所有元素
        Collections.sort(list);//将集合中元素按照升序排序,参数只能穿list集合
        System.out.println(list);
        ____________________________________________________
		//String排序:
		ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list,"d","e","c","a","b");//往集合中添加所有元素
        Collections.sort(list);
        System.out.println(list);
	   ____________________________________________________
		//自定义类型排序(自定义类)
		public class Student implements Comparable<Student> {
		    private String name;
		    private int age;
		    //省略了toString/构造/geter/setter等...

		    //重写排序规格
		    @Override
		    public int compareTo(Student o) {
		        return this.getAge()-o.getAge();//按照年龄升序排序
		        //return 0;//默认的return 0;是认为元素都是相同的
		        
		       /* 
		       Comparable接口排序规格
				自己(this.)-参数(o.):升序
				参数(o.)-自己(this.):降序
				*/
		    }
		}

		//业务代码中就可以对这个类排序了.......
		Collections.sort(Student);

3.4、Collections.sort(list, new Comparator())自定义排序

		//比较自定义类(方法一)
        List<Student> list = new ArrayList<>();
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //按照 int类型 年龄排序-->升序
                int result = o1.getAge()-o2.getAge();
                //如果年龄相同,再使用姓名第一个字 String类型 排序(升序)
                if(result == 0){
                    result = o1.getName().charAt(0)-o2.getName().charAt(0)
                }
                return result;
            }
        });
       ____________________________________________________
		//自定义类型排序(方法二:java8 写法)
		
		List<Student> list= new ArrayList<>;// 创建集合
		//日期字符串排序 节次排序(Student属性 bitherday和number 为String类型)
		Comparator<Student> comparingDate = Comparator.comparing(Student::getBitherday);
		Comparator<Student> comparingNUM = Comparator.comparing(Student::getNumber).reversed();//降序
		// 多个字段联合排序:生日升序,number降序
		list.sort(comparingDate.thenComparing(comparingNUM));

3.5 其他CollectionUtils

// 判断 集合(list/set/map) 是否为空
CollectionUtils.isEmpty(集合)
// 判断 List/Set 中是否包含某个对象
CollectionUtils.containsInstance(Collection collection, Object element)
// 判断 List/Set 是否包含小集合
CollectionUtils.containsAny(Collection big, Collection small)
// 返回 List/Set 中最后一个元素
CollectionUtils.lastElement( list)  

// 两个集合取交集
Collection<String> collection = CollectionUtils.retainAll(listA, listB);
// 两个集合取并集
Collection<String> collection = CollectionUtils.union(listA, listB);
// 两个集合取差集
Collection<String> collection = CollectionUtils.subtract(listA, listB);

3.5 Collections.singleton(null) 去除 null 元素

//去除 null 元素
oldList.removeAll(Collections.singleton(null)); 
//去除 空 元素
oldList.removeAll(Collections.singleton("")); 

4.Hash值

定义:hash值是一个十进制的整数,由本地系统(native)随机给出(就是对象的地址值,是一个逻辑地址,是模拟出来的地址,不是数据实际存储的物理地址)

.hashCode()//获取hash值

哈希冲突:两个元素不同,但是哈希值相同就是哈希冲突.

哈希表结构查询数据快的原因:
是因为先根据hash值分组了,将hash值相同的元素挂到一个链表上,如果挂载的元素超过8位就将这个链表的结构转换为红黑树.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值