Java集合深入学习 - Iterator/Iterable/Collection/List/Set/Map接口定义(基于jdk1.8)

1.Iterator接口定义

/**
 * iterator为Java中的迭代器对象,是能够对List这样的集合进行迭代遍历的底层依赖。
 */
public interface Iterator<E> {
    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

2.Iterable 接口定义

/**
 * iterable接口里定义了返回iterator的方法,相当于对iterator的封装
 * 	实现了iterable接口的类可以支持for each循环。
 */
public interface Iterable<T> {
    Iterator<T> iterator();

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

    default Spliterator<T> spliterator() {
        return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }
}

3.Collection接口定义


/**
 * 定义集合接口 继承迭代器类
 */
public interface Collection<E> extends Iterable<E> {
	//集合大小
	int size();
	//是否为空
    boolean isEmpty();
    //是否包含数据o
    boolean contains(Object o);
    //获取迭代器
    Iterator<E> iterator();
    //转换数据成Object[]
    Object[] toArray();
    //转换数据成T[]
    <T> T[] toArray(T[] a);
    //添加数据
    boolean add(E e);
    //删除数据
    boolean remove(Object o);
    /** 集合相关操作 */
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean removeAll(Collection<?> c);
    boolean retainAll(Collection<?> c);
    default boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator<E> each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
        return removed;
    }
    
    //清空集合
    void clear();
    /** equals和hashCode */
    boolean equals(Object o);
    int hashCode();
    
    @Override
    default Spliterator<E> spliterator() {
    	return null;
    }
    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}

4.List接口定义


/**
 * 定义List 接口  继承 集合接口Collection
 */
public interface List<E> extends Collection<E> {
	/** 继承自 Collection的方法*/
	int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator<E> iterator();
    Object[] toArray();
    <T> T[] toArray(T[] a);
    boolean add(E e);
    boolean remove(Object o);
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean addAll(int index, Collection<? extends E> c);
    boolean removeAll(Collection<?> c);
    boolean retainAll(Collection<?> c);
    default void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final ListIterator<E> li = this.listIterator();
        while (li.hasNext()) {
            li.set(operator.apply(li.next()));
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

    void clear();
    boolean equals(Object o);
    int hashCode();

    /** 新增方法*/
    //根据下标获取数据
    E get(int index);
    //根据下标修改数据
    E set(int index, E element);
    //指定位置插入数据
    void add(int index, E element);
    //删除指定位置数据
    E remove(int index);
    //从前往后获取数据出现位置下标
    int indexOf(Object o);
    //从后往前获取数据出现位置下标
    int lastIndexOf(Object o);

    /** 获取 ListIterator 迭代器*/
    ListIterator<E> listIterator();
    ListIterator<E> listIterator(int index);

    List<E> subList(int fromIndex, int toIndex);

    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, Spliterator.ORDERED);
    }
}

5.Set接口定义

/**
 * Set接口继承Collection 接口  无新增方法
 */
public interface Set<E> extends Collection<E> {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator<E> iterator();
    Object[] toArray();
    <T> T[] toArray(T[] a);
    boolean add(E e);
    boolean remove(Object o);
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean retainAll(Collection<?> c);
    boolean removeAll(Collection<?> c);
    void clear();
    boolean equals(Object o);
    int hashCode();
    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, Spliterator.DISTINCT);
    }
}

6.Map接口定义

/**
 * Map接口
 */
public interface Map<K,V> {
	/** 返回数据大小 */
    int size();
    /** 是否为空 */
    boolean isEmpty();
    /** key是否存在 */
    boolean containsKey(Object key);
    /** value是否存在 */
    boolean containsValue(Object value);
    /** 获取数据  */
    V get(Object key);
    /** 添加数据 */
    V put(K key, V value);
    /** 删除数据 */
    V remove(Object key);
    /** 将一个Map中的数据全部添加到该map中 */
    void putAll(Map<? extends K, ? extends V> m);
    /** 清空Map */
    void clear();
    /** 所有key的集合 */
    Set<K> keySet();
    /** 所有value的集合 */
    Collection<V> values();
    /** 所有节点集合 */
    Set<Map.Entry<K, V>> entrySet();

    /**
     * Map接口中的节点接口定义
     */
    interface Entry<K,V> {
    	/** 获取key */
        K getKey();
        /** 获取value */
        V getValue();
        /** 设置value*/
        V setValue(V value);
        /** hashCode与equals方法 */
        boolean equals(Object o);
        int hashCode();
        
        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
        }
        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getValue().compareTo(c2.getValue());
        }
        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
        }
        public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
        }
    }

    /** equals与hashCode */
    boolean equals(Object o);
    int hashCode();
    
    /** 获取数据  未查到数据时返回默认值defaultValue */
    default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

    /** 消费者接口处理 */
    default void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        for (Map.Entry<K, V> entry : entrySet()) {	//遍历所有节点
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                throw new ConcurrentModificationException(ise);
            }
            action.accept(k, v);	//函数式接口处理
        }
    }

    /** 函数式接口处理  */
    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        for (Map.Entry<K, V> entry : entrySet()) {	//遍历所有节点
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                throw new ConcurrentModificationException(ise);
            }

            v = function.apply(k, v);	//对结果进行处理

            try {
                entry.setValue(v);		//节点value重新赋值
            } catch(IllegalStateException ise) {
                throw new ConcurrentModificationException(ise);
            }
        }
    }

    /** 不覆盖添加数据 */
    default V putIfAbsent(K key, V value) {
        V v = get(key);
        if (v == null) {
            v = put(key, value);
        }

        return v;
    }

    /** 删除数据 */
    default boolean remove(Object key, Object value) {
        Object curValue = get(key);	//获取节点
        if (!Objects.equals(curValue, value) ||
            (curValue == null && !containsKey(key))) {	//key不存在
            return false;
        }
        remove(key);	//处理成功
        return true;
    }

    /** 修改数据 */
    default boolean replace(K key, V oldValue, V newValue) {
        Object curValue = get(key);	//获取key原来对应的value
        if (!Objects.equals(curValue, oldValue) ||	
            (curValue == null && !containsKey(key))) {
            return false;	//节点(key = key  value = oldValue)不存在
        }
        put(key, newValue);	//修改节点数据
        return true;
    }

    /** 修改数据 */
    default V replace(K key, V value) {
        V curValue;
        if (((curValue = get(key)) != null) || containsKey(key)) {	//key存在
            curValue = put(key, value);	//修改节点数据
        }
        return curValue;
    }

    /** 函数式接口处理  -对单个key操作 */
    default V computeIfAbsent(K key,
            Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = get(key)) == null) {	//获取节点value值
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {	//处理value
                put(key, newValue);	//重新赋值
                return newValue;	//返回新结果
            }
        }
        return v;
    }

    /** 函数式接口处理  -对单个key操作 */
    default V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue;
        if ((oldValue = get(key)) != null) {
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != null) {
                put(key, newValue);
                return newValue;
            } else {
                remove(key);
                return null;
            }
        } else {
            return null;
        }
    }

    /** 函数式接口处理  -对单个key操作  */
    default V compute(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = get(key);

        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            if (oldValue != null || containsKey(key)) {
                remove(key);
                return null;
            } else {
                return null;
            }
        } else {
            put(key, newValue);
            return newValue;
        }
    }

    /** 函数式接口处理 */
    default V merge(K key, V value,
            BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        Objects.requireNonNull(value);
        V oldValue = get(key);
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue, value);
        if(newValue == null) {
            remove(key);
        } else {
            put(key, newValue);
        }
        return newValue;
    }
}

猜你喜欢

转载自blog.csdn.net/luo_mu_hpu/article/details/106275477