Have you mastered these collection operations of Java 8?

If you don't know about lambda, you can refer to my previous summary on lambda expression: lambda expression in Java 8. Would you like to?

For the set class, let's sort out the changes.

Iterable foreach

The iteratable interface is the parent interface of all iteratable types, and the well-known collection interface inherits from it. The default method of Java 8 interface and the appearance of lambda expression make it very easy for us to operate on elements when traversing elements.

The following foreach method is new in Java 8. It accepts a consumer object and is a functional interface of consumer type.

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

The following code iterates through each element of the output.

    public void testForEach(){
        List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        list.forEach(System.out::println);
    }

Foreachremaining of iterator

java. util. Iterator is an iterator used to traverse a collection. The interface is defined as follows:

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());
    }
}

The default method is newly added in the Java 8 interface. The foreachremaining method receives a consumer. We can simplify our traversal operation through this method:

    /**
     * Java8 为Iterator新增了 forEachRemaining(Consumer action) 方法
     */
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(Arrays.asList(1,5));
        Iterator<Integer> iterator = list.iterator();
        iterator.forEachRemaining(System.out::println);
    }

Removeif of collection

Java 8 adds a default removeif method to the collection to receive a predicate judgment. If the test result is true, the corresponding element will be removed.

    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;
    }

The following code removes even elements from the list.

    public void testRemoveIf() {
        List<Integer> list = new ArrayList<>(Arrays.asList(1,5));
        list.removeIf(x -> x % 2 == 0);
        list.forEach(System.out::println);
    }

Stream operation

For specific use, please refer to the summary of common methods of Java 8's stream API

    public void testStream(){
        IntStream stream = IntStream.builder().add(1).add(2).add(3).build();
        int max = stream.max().getAsInt();
        System.out.println(max);
    }

Replaceall of list

Java 8 adds the default replaceall method to the list interface, which requires unaryoperator to replace all collection elements. Unaryoperator is a functional interface.

    default void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final ListIterator<E> li = this.listIterator();
        while (li.hasNext()) {
            li.set(operator.apply(li.next()));
        }
    }

The following example adds 3 to each element.

    public void testReplaceAll(){
        List<Integer> list = new ArrayList<>(Arrays.asList(1,5));
        list.replaceAll(x -> x + 3);
        list.forEach(System.out::println);
    }

Sort of list

Java 8 adds a default sort method to the list interface. The comparator object is required to control the element row. We can pass in a lambda expression.

    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);
        }
    }

The following example will reverse the list.

    public void testSort() {
        List<Integer> list = new ArrayList<>(Arrays.asList(1,5));
        list.sort((x,y) -> y - x);
        System.out.println(list);
    }

Foreach of map

The map interface also adds a method for traversal in Java 8:

    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) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
            action.accept(k,v);
        }
    }

This method receives a binary parameter, corresponding to key and value respectively:

    private void print(Map<Integer,String> map){
        map.forEach((x,y )-> {
            System.out.println("x -> " + x + ",y -> " + y);
        });
    }

For the convenience of the next test, prepare the data first:

    Map<Integer,String> map = new HashMap<>();

    {
        map.put(1,"hello");
        map.put(2,"summer");
        map.put(3,"day");
        map.put(4,"tqbx");
    }

Remove of map

Java 8 adds a remove (object key, object value) method.

    default boolean remove(Object key,Object value) {
        // key存在且key对应的value确实是传入的value才移除
        Object curValue = get(key);
        if (!Objects.equals(curValue,value) ||
            (curValue == null && !containsKey(key))) {
            return false;
        }
        remove(key);
        return true;
    }

Remove the element with key 3 and value day.

    @Test
    public void testRemove(){
        map.remove(3,"day");
        print(map);
    }

Compute related methods of map

Object compute (object key, bifunction, remappingfunction): this method uses remappingfunction to calculate a new value according to the key value pair, as follows:

Object computeIfAbsent(Object key,Function mappingFunction):

Object computeIfPresent(Object key,BiFunction remappingFunction):

    @Test
    public void testCompute() {
        //key==2 对应的value存在时,使用计算的结果作为新value
        map.computeIfPresent(2,(k,v) -> v.toUpperCase());
        print(map);

        //key==6 对应的value为null (或不存在)时,使用计算的结果作为新value
        map.computeIfAbsent(6,(k) -> k + "haha");
        print(map);
    }

Getordefault of map

    default V getOrDefault(Object key,V defaultValue) {
        V v;
        // key存在或 value存在,则返回对应的value,否则返回defaultValue
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }
    @Test
    public void testGetOrDefault(){
        // 获取指定key的value,如果该key不存在,则返回default
        String value = map.getOrDefault(5,"如果没有key==5的value,就返回这条信息");
        System.out.println(value);
    }

Merge of map

    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);
        // 原值为null,新值则为传入的value,不为null,则使用function计算,得到新值
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue,value);
        // 新值如果为null,则移除原key-value对
        if(newValue == null) {
            remove(key);
        } else {
            // 不为null,则替换之
            put(key,newValue);
        }
        // 返回新值
        return newValue;
    }
    @Test
    public void testMerge(){
        // key为2 的值 加上 +add
        map.merge(2," + add",(oldval,newVal) -> oldval + newVal);
        print(map);
    }

Putifabsent of map

    default V putIfAbsent(K key,V value) {
        // 得到原值
        V v = get(key);
        // 原值为null,则替换新值
        if (v == null) {
            v = put(key,value);
        }
		// 返回原值
        return v;
    }
    @Test
    public void testPutIfAbsent(){
        // key = 10 对应的value不存在, 则用101010 覆盖
        String s1 = map.putIfAbsent(10,"101010");
        System.out.println(s1);
        print(map);
        System.out.println("============================");
        // key = 2 对应的value存在且为summer,返回summer
        String s2 = map.putIfAbsent(2,"2222");
        System.out.println(s2);
        print(map);
    }

Output results

null
x -> 1,y -> hello
x -> 2,y -> summer
x -> 3,y -> day
x -> 4,y -> tqbx
x -> 10,y -> 101010
============================
summer
x -> 1,y -> 101010

Replace related methods of map

    @Test
    public void testReplace(){
        //boolean 将指定的 1 -> hello 键值对的value替换为hi
        map.replace(1,"hello","hi");
        print(map);
        System.out.println("============================");
        //V 指定key对应的value替换成新value
        map.replace(2,"天乔巴夏");
        print(map);
        System.out.println("============================");
        //void 对所有的key和value 进行计算,填入value中
        map.replaceAll((k,v)-> k + "-" + v.toUpperCase());
        print(map);
    }

Output results:

x -> 1,y -> hi
x -> 2,y -> tqbx
============================
x -> 1,y -> 天乔巴夏
x -> 3,y -> 1-HI
x -> 2,y -> 2-天乔巴夏
x -> 3,y -> 3-DAY
x -> 4,y -> 4-TQBX
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>