20210907-java集合

目录

1、java中的集合

2、Collection中的排序

3、Collections的排序

4、List中的排序

5、Queue中的排序

6、Vector排序

7、HashMap排序

8、HashSet排序

9、LinkedHashSet排序

10、TreeSet排序

11、ArrayList和LinkedList之间的区别

1、java中的集合

 Java集合框架支持以下两种类型的容器:

 一种是为了存储一个元素集合,简称为集合(collection)。

 另一种是为了存储键/值对,称为映射表(map)。

java集合中的框架:

 

2、Collection中的排序

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
 * List:有序(插入顺序)
 * 		ArrayList:底层采用数组来实现
 * 		数组特点:地址连续;寻址简单;
 * 				根据索引加载数据效率非常高
 * 
 *
 */
public class CollectionDemo {
	public static void main(String[] args) {
		Collection<String> names = new ArrayList<>();
		names.add("peppa");
		names.add("emily");
		names.add("pedro");
		names.add("suzy");
		
		System.out.println(names);
		names.remove("pedro");
		System.out.println(names.size());
		
		Collection<String> collection = new ArrayList<String>();
		collection.add("denny");
		collection.add("candy");
		collection.add("rebbca");
		collection.add("emily");
		collection.add("pedro");
		collection.add("pedro");
		//将两个集合元素进行合并
		names.addAll(collection);
		System.out.println(names);
//		names.removeAll(collection);
//		names.retainAll(collection);
		System.out.println(names);
		
		//通过for-each
		for(String name : names) {
			System.out.print(name + " ");
		}
		System.out.println();
		//通过迭代集合中的每个元素
		Iterator<String> iterator = names.iterator();
		while(iterator.hasNext()) {
			System.out.print(iterator.next() + " ");
		}
		
		//通过foreach
		names.forEach(name->System.out.print(name + " "));
		names.forEach(System.out::print);
	}
}

3、Collections的排序

        Collections中是需要提供一个比较器Comparator,才能进行比较。

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

public class CollectionsDemo {
	public static void main(String[] args) {
		List<Circle> circles = new ArrayList<Circle>();
		circles.add(new Circle(5));
		circles.add(new Circle(15));
		circles.add(new Circle(3));
		circles.add(new Circle(10));
		
//		Collections.sort(circles);//自然排序,要求集合中的元素时Comparable类型
//		for(var circle : circles)
//			System.out.println(circle);
		
		//比较排序,提供一个比较器Comparator
		Collections.sort(circles, (c1,c2)->{return c1.getRadius() == c2.getRadius() ? 0 
				:c1.getRadius() > c2.getRadius() ? 1 : -1;});
		//for each原理:内部使用迭代器实现的
		for(var circle : circles)
			System.out.println(circle);
		
		Collections.reverse(circles);
		System.out.println("======================");
		var iterator = circles.iterator();
		
	}
}

4、List中的排序

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListDemo {
	public static void main(String[] args) {
		List<Integer> list1 = new ArrayList<Integer>();
		LinkedList<Integer> list2 = new LinkedList<Integer>();
		long start = System.currentTimeMillis();
		for(int i = 0; i < 20000000; i++) {
			list1.add(0,i);
		}
		System.out.println("元素个数:" + list1.size());
		System.out.println(System.currentTimeMillis() - start);
		
		for(int i = 0; i < 20000000; i++) {
			list2.addFirst(i);
		}
		System.out.println("元素个数:" + list2.size());
		System.out.println(System.currentTimeMillis() - start);
		System.out.println("===============");
		start = System.currentTimeMillis();
		for(int i = 0; i < list1.size(); i++) {
			list1.get(i);
			
		}
		System.out.println(System.currentTimeMillis() - start);
		
		for(int i = 0; i < list2.size(); i++) {
			list2.get(i);
			
		}
		System.out.println(System.currentTimeMillis() - start);
	}
}

5、Queue中的排序

import java.util.Deque;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 *队列:先进先出
 *
 */
public class QueueDemo {
	public static void main(String[] args) {
		
//		deque();
		priority();
	}
	
	public static void queue() {
		Queue<String> queue = new LinkedList<String>();
		queue.offer("peppa");
		queue.offer("eimly");
		queue.offer("suzy");
		queue.offer("pedro");
		
		System.out.println(queue);
		
		while(!queue.isEmpty()) {
			System.out.print(queue.poll() + " ");
		}
	}
	
	public static void deque() {
		Deque<String> queue = new LinkedList<String>();
		queue.offer("peppa");
		queue.offerFirst("suzy");
		queue.offerLast("pedro");
		
		while(!queue.isEmpty()) {
			System.out.print(queue.pollLast() + " ");
		}
	}
	
	public static void priority() {
		 PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
	        queue.add(10);
	        queue.add(20);
	        queue.add(20);
	        queue.add(30);
	        queue.add(10);
	        queue.add(40);
	        
	        while(queue.size() > 0)
	            System.out.print(queue.remove() + " ");//最高优先级最先被删除
	        
	        //也可以使用构造方法PriorityQueue(initialCapacity,comparator)中的comparator来指定一个顺序
	        //Collections.reverseOrder():逆序比较器
//	        System.out.println();
//	        PriorityQueue<Integer> queue2 = new PriorityQueue<Integer>(Collections.reverseOrder());
//	        queue2.add(10);
//	        queue2.add(20);
//	        queue2.add(20);
//	        queue2.add(30);
//	        queue2.add(10);
//	        queue2.add(40);
//	        while(queue2.size() > 0)
//	            System.out.print(queue2.remove() + " ");//最高优先级最先被删除
	}
}

6、Vector排序

import java.util.Vector;

/**
 * 除了包含用于访问和修改向量的同步方法之外,Vector和ArrayList是一样的,底层都是采用数组存取数据	
 *	Vector:线程同步的
 *	ArrayList:非线程同步
 */
public class VectorDemo {
	public static void main(String[] args) {
		Vector<String> vector = new Vector<String>();
		vector.addElement("peppa");
		vector.add("pedro");
	}
}

7、HashMap排序

        map底层用红黑树实现。

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import edu.uestc.avatar.demo.Circle;
/**
 * Map存放键值对
 * 		键值可以是任意类型的对象,键不重复(会被覆盖),值可以重复
 * 	HashMap:键值对无序的,底层采用散列表实现
 * 	LinkedHashMap:使用一个链表类来扩展HashMap,支持key的顺序(插入顺序;访问顺序)
 * 	TreeMap:使用treeMap可以对key进行定制排序(自然排序;比较排序);迭代排好序的散列表效率非常高
 * 
 * 如果没有顺序要求:使用HashMap;如果需要按照插入顺序或者访问顺序进行排序,就是LinkedHashMap
 *
 */
public class HashMapDemo {
	
	public static void main(String[] args) {
		Map<Integer, String> map = new HashMap<Integer, String>();
		//向map中添加键值对
		map.put(1020, "peppa");
		map.put(9527, "jorge");
		map.put(1000, "jorge");
		map.put(1000, "suzy");
		map.put(null, null);

		System.out.println("map中的条目数:" + map.size());
		
		//根据key快速定位元素(查找)
		System.out.println(map.get(1020));
		System.out.println(map.get(null));
		System.out.println(map.get(2000));
		System.out.println(map.getOrDefault(2000, "pedro"));
		
		//修改值
		map.replace(null, "emily");
		System.out.println(map.get(null));
		
		//删除键值对
		map.remove(null);//根据key删除键值对
		
		//判断map中是否存在指定的key
		System.out.println(map.containsKey(1020));//包含为true
		System.out.println(map.containsKey("pedro"));//包含为true
		
		
		System.out.println("====================================");
		//迭代map的几种方式:
		//1、获取map所有的key,根据key去加载键值对
		Set<Integer> keys = map.keySet();
		for(Integer key : keys)
			System.out.println("key:" + key + ",value=" + map.get(key));
		System.out.println("==============================");
		//2、遍历map中所有的value
		Collection<String> names = map.values();
		for(String name : names)
			System.out.println(name);
		System.out.println("==============================");
		//3、迭代map中所有的条目(key和value组成了Entry)
//		Set<Entry<Integer,String>> entrys = map.entrySet();
		for(Entry<Integer,String> entry : map.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
		System.out.println("================================");
		
		//4、通过map提供的foreach迭代
		map.forEach((k,v)->System.out.println(k + ":" + v));
		
//		linkedHashMapDemo();
		
		treeMapDemo();
	}
	
	/**
	 * emp表
	 * 	empno
	 * 	ename
	 * 	job
	 * 	sal
	 * 	comm
	 * 	hire_date
	 * 
	 * select empno,ename,job,sal,comm,hire_date from emp
	 * order by hire_date,desc,sal,desc
	 */
	public static void linkedHashMapDemo() {
		var sorted = new LinkedHashMap<String, String>();
		sorted.put("hire_date","asc");
		sorted.put("sal","desc");
		sorted.put("comm","desc");
		sorted.put("job","asc");
		
		StringBuilder sb = new StringBuilder("select empno,ename,job,sal,comm,hire_date from emp");
		if(sorted != null && sorted.size() > 0) {
			sb.append(" order by ");
			sorted.forEach((k,v)->sb.append(k).append(' ').append(v).append(','));
			sb.deleteCharAt(sb.length() - 1);
		}
		System.out.println(sb.toString());
	}
	
	public static void treeMapDemo() {
		var map = new TreeMap<Float, Circle>();
		map.put(5F, new Circle(5));
		map.put(3F, new Circle(3));
		map.put(1F, new Circle(1));
		map.put(10F, new Circle(10));
		
		map.forEach((k,v)->System.out.println(v));
	}
}

map.forEach((k,v)->System.out.println(v));

上述语句中用的是java中的Lambda表达式。

8、HashSet排序

import java.util.HashSet;
import java.util.Set;

import edu.uestc.avatar.demo.Circle;

/**
 * 数组:
 * 	  有序,地址连续,寻址容易;而在特定位置进行增删效率极低
 * 链表:
 * 	  有序(逻辑上),物理地址并不连续;寻址较困难;在头进行增删效率非常高
 * 散列表:
 *     数组加链表(红黑树) 
 * 
 * Set用于存储一组不重复的元素
 * 		HashSet是Set集合的一个具体实现,用于存储不重复元素,无序的;底层采用的HashMap实现
 *      LinkedHashSet:是HashSet的一个扩展,HashSet是无序的,
 *      	LinkedHashSet内部维护了一个按照添加顺序列表元素的双端链表;内部采用LinkedHashMap实现
 *      TreeSet:
 *      	可以定制排序(自然排序/比较排序);默认采用自然排序:内部采用TreeMap实现 TreeMap是(红黑树实现)。
 *
 */
public class HashSetDemo {
	public static void main(String[] args) {
		Set<String> names = new HashSet<String>();
		names.add("peppa");
		names.add("suzy");
		names.add("pedro");
		names.add("peppa");
		names.add("pedro");
		
		System.out.println(names.size());
		for(String name : names)
			System.out.print(name + " ");
		System.out.println("===============");
		Set<Circle> circles = new HashSet<Circle>();
		
		circles.add(new Circle(10));
		circles.add(new Circle(20));
		circles.add(new Circle(30));
		
		circles.add(new Circle(20));
		circles.add(new Circle(10));
		
		var iterator = circles.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		circles.remove(new Circle(10));
		System.out.println(circles.size());
	}
}

9、LinkedHashSet排序

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetDemo {
	public static void main(String[] args) {
		Set<String> names = new LinkedHashSet<String>();
		names.add("peppa");
		names.add("suzy");
		names.add("pedro");
		names.add("peppa");
		names.add("pedro");
		names.add("dannie");
		
		System.out.println(names.size());
		for(String name : names)
			System.out.print(name + " ");
	}
}

10、TreeSet排序

import java.util.Set;
import java.util.TreeSet;

import edu.uestc.avatar.demo.Car;
import edu.uestc.avatar.demo.Circle;

public class TreeSetDemo {
	public static void main(String[] args) {
		Set<String> names = new TreeSet<String>();
		names.add("peppa");
		names.add("suzy");
		names.add("pedro");
		names.add("peppa");
		names.add("pedro");
		names.add("dannie");
		
		System.out.println(names.size());
		for(String name : names)
			System.out.print(name + " ");
		System.out.println("===============");
		//默认采用自然排序
		Set<Circle> circles = new TreeSet<Circle>();
		
		circles.add(new Circle(10));
		circles.add(new Circle(20));
		circles.add(new Circle(30));
		
		circles.add(new Circle(20));
		circles.add(new Circle(10));
		
		for(var circle : circles)
			System.out.println(circle);
		//使用比较排序去指定排序规则
				Set<Car> cars = new TreeSet<>(
//						(car1,car2)->car1.getBrand().compareTo(car2.getBrand())
						(car1,car2)->car1.getColor().compareTo(car2.getColor())
						);
				cars.add(new Car("Benz", "black"));
				cars.add(new Car("BMW", "sliver"));
				cars.add(new Car("Audi", "yellow"));
				cars.add(new Car("cadillac", "red"));
				System.out.println("=========================");
				for(Car car : cars)
					System.out.println(car.getBrand());
			}
		}

11、ArrayList和LinkedList之间的区别

        ①ArrayList是基于数组实现的,LinkedList是基于一种双向链表实现。

        ②LinkedList可以快速查找第一个和最后一个元素,ArrayList是需要从第一个开始遍历,ArrayList添加元素会进行向后移位,会导致数组元素产生变化,不便管理,通常情况下我们都是通过LinkedList进行添加元素。

LinkedList源码:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

源码分析:继承自AbstractSequentialList<E>这个类,实现了List<E>接口,双队列接口,标记接口,调用clone实现克隆,序列化接口。

ArrayList源码:

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

该元素数据是默认容量为空的元素数据。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值