Java Study Notes 14 Collection

Set collection

The Set interface inherits the Collection interface, and the elements in the collection cannot be repeated. If there are related elements with repeated content, the original elements will be retained, and the added elements will be canceled. Elements cannot be read randomly, and there is no order.

 Set<Integer> set1 = new HashSet<>();
        //添加元素
        set1.add(1);
        set1.addAll(List.of(2, 3, 4, 5, 6, 1, 9));
        System.out.println(set1);
        //判断有没有元素
        System.out.println(set1.contains(5));
        System.out.println(set1.contains(7));
        System.out.println(set1.containsAll(List.of(1, 23, 3, 4)));
        System.out.println("=========================================");
        //删除元素
        System.out.println(set1.remove(9));
        System.out.println(set1);
        set1.clear();
        System.out.println(set1);

insert image description here
Objects in the HashSet collection must override the following two methods: equals() hashCode(), which can be automatically generated using advanced tools.

public class StudentsA1 implements Comparable

 @Override
    public int compareTo(StudentsA1 o) {
    
    
        return id - o.id;
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) {
    
    
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
    
    
            return false;
        }
        StudentsA1 that = (StudentsA1) o;
        return id == that.id;
    }

The Set collection is traversed, and one of them cannot be read randomly, or all of them have been read.

for (int i : set1) {
    
    
            System.out.println(i);
        }

TreeSet

It is an ordered, sortable, non-repeatable collection tool class.

		TreeSet<Integer> tree = new TreeSet<>();
        //加入的时候会自动排序
        tree.addAll(List.of(1, 2, 3, 44, 66, 44, 1, 2, 6, 5, 4));
        System.out.println(tree.size());
        System.out.println(tree);

        TreeSet<String> trees = new TreeSet<>();
        trees.addAll(List.of("java", "python", "c", "c++", "javascript", "book", "java"));
        System.out.println(trees.size());
        System.out.println(trees);

insert image description here

The collation can be modified.

 TreeSet<String> trees = new TreeSet<>((a, b) -> b.compareTo(a));
        trees.addAll(List.of("java", "python", "c", "c++", "javascript", "book", "java"));
        System.out.println(trees.size());
        System.out.println(trees);

insert image description here

Tool class of Collections interface

The java.util.Collections tool class is equivalent to the tool class Arrays tool class of the array object

Sort operation

  1.    reverse(List):反转List中元素的顺序
    
  2.    shuffle(List):对List集合元素进行随机排序
    
  3.    sort(List):根据元素的自然顺序对指定List集合元素按升序排序
    
  4.    sort(List,Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序
    

replace and find operations

  1.    swap(List, int ,int ):将指定List集合中的 i 处元素 和 j 处元素进行交换
    
  2.    Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
    
  3.  Object max(Collection, Comparator):根据Comparator指定的顺序,返回给集合中的最大元素
    
  4.    Object min(Collection):根据元素的自然顺序,返回给定集合中的最小元素
    
  5.    Object min(Collection, Comparator):根据Comparator指定的顺序,返回给集合中的最大元素
    
  6.   int frequency(Collection,Object):返回指定集合中指定元素的出现次数
    
  7.   void copy(List dest,List src):将src中的内容复制到dest中
    注意复制的目标集合的长度必须大于源集合,否则会抛出空指针异常
    
  8. boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换List对象的所有旧值
    
		List<Integer> list = new ArrayList<>(List.of(10,20,30,40,50,10));
        System.out.println(list);

        //洗牌
        Collections.shuffle(list);
        System.out.println(list);

        //升序
        Collections.sort(list);
        System.out.println(list);

        //降序
        Collections.sort(list,(a,b)->b-a);
        System.out.println(list);

        //集合位置交换,倒序
        Collections.reverse(list);
        System.out.println(list);

Map interface

public interface Map<K, V> {
}

The implementation class of Map<K,V> is HashMap<K,V>, HashMap instantiates, adds, judges, clears, deletes, replaces

When adding elements, write new values ​​to overwrite when K repeats.

K will not be overwritten if it does not repeat the value.

Map<String, String> map = new HashMap<>();
        map.put("bj", "北京");
        map.put("tj", "天津");
        map.put("hn", "河南");
        map.put("sh", "上海");
        //第一种遍历方式 keySet()方法返回Set集合
        Set<String> keys = map.keySet();
        for (String k : keys) {
    
    
            System.out.printf("map[\"%s\"] = %s%n", k, map.get(k));
        }

        System.out.println("1111111111111111111111111");

        //第二种遍历方式 values() 返回Collection<String> 集合
        Collection<String> values = map.values();
        for (String v : values) {
    
    
            System.out.println(v);
        }
        System.out.println("2222222222222222222222222222");
        //第三种遍历方式 entrySet() 返回一个Set<Map.Entry<String,String>> 集合
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> e : entries) {
    
    
            System.out.println(e.getKey());
            System.out.println(e.getValue());
        }
        System.out.println("333333333333333333333333333333");

        //第四种遍历方式 使用迭代器接口Iterator 接口
        Iterator<String> iterator = map.values().iterator();
        while (iterator.hasNext()) {
    
    
            System.out.println(iterator.next());
        }
        System.out.println("44444444444444444444444444444");
        Iterator<String> iterator1 = map.keySet().iterator();
        while (iterator1.hasNext()) {
    
    
            String key = iterator1.next();
            System.out.println(key);
            System.out.println(map.get(key));
        }
Map<String, String> map = new HashMap<>();
        map.put("bj", "北京");
        map.put("tj", "天津");
        map.put("hn", "河南");
        map.put("sh", "上海");
        System.out.println(map.size());
        //获取值
        System.out.println(map.get("hn"));
        //判断有没有值
        System.out.println(map.containsKey("hn"));
        //获取值
        if (map.containsKey("hn")) {
    
    
            System.out.println(map.get("hn"));
        }

HashMap is not thread-synchronized. If you need to use thread concurrency, you can use HashTable object.

Hashtable<K,V> implements Map<K,V>

Hashtable: The bottom layer is also a hash table, which is synchronous, a single-thread combination, and a thread-safe collection, which is slow

HashMap: The underlying layer is also a hash table, but it is a thread-unsafe collection. It is a multi-threaded collection with fast speed.

HashMap (and all the collections learned before): can store null keys, null values

Hashtable: Cannot store null key, null value

TreeMap

TreeMap is not thread synchronized.
  1. It is an ordered key-value collection, which is realized through a red-black tree. The map is sorted according to the natural order of its keys, or according to the Comparator provided when the map was created, depending on the constructor used.

  2. It inherits from AbstractMap and is also stored in a key-value collection. Implemented the NavigableMap interface, which can support a series of navigation methods.

    For example, return an ordered set of keys. Implements the Cloneable clone interface.

		TreeMap<Integer, String> tm = new TreeMap<>();
        tm.put(1, "hello1");
        tm.put(2, "hello22");
        tm.put(3, "hello333");
        tm.put(10, "hello10");
        tm.put(4, "hello4444");
        System.out.println(tm);
        //.descendingMap() 返回一个Map 根据key降序,对原来的TreeMap没有改变
        Map<Integer, String> t2 = tm.descendingMap();
        System.out.println(tm);
        System.out.println(t2);

insert image description here

method illustrate
put(K key, V value) associates the specified value with the specified key in this map
int size() Returns the number of elements in this collection
V remove(Object key)
putAll(Map map) Copies all mappings in the specified mapping into this mapping
Collection values()
Set keySet() The essence is TreeSet
Map.Entry<K,V> entrySet() returns Set<Map.Entry<K,V>>
get(Object key)
containsKey(Object key)
firstEntry() Return the first Map.Entry<K,V> in the collection
lastEntry()
firstKey() Returns the Key of the first element of the collection
lastKey()
boolean remove(Object key, Object value)
containsValue()

Collection interface and tool class summary:

Collection interface
List interface
ArrayList dynamic array, ordered insertion and deletion speed is slow, reading speed
LinkedList doubly linked list, insertion and deletion speed is fast, reading speed
Vector dynamic array, thread-safe
Set interface
HashSet unique collection, unordered
TreeSet unique collection, yes orderly

Map interface
HashMap K, V key-value pair collection, double-column collection
TreeMap An ordered map collection according to key
Hashtable Same as HashMap, double-column collection, thread-safe

Guess you like

Origin blog.csdn.net/xxxmou/article/details/129190244
Recommended