Java 8 data filtering, removeif and filter don’t use them wrong!!

Time:2021-10-12

Filter is the method of java8 stream:

Stream filter(Predicate super T> predicate)

Returns a stream consisting of elements of this stream that match this given predicate.

Removeif is a default method for Java 8 collection.

default boolean removeIf(Predicate super E> filter)

Deletes all elements of this collection that satisfy the given predicate.

Both removeif and filter methods can filter / delete elements.

In terms of function implementation, removeif means that if the condition is true, this element is filtered, and if false, it is retained. Filter filters this element when the condition is false, while true keeps it.

In terms of time, it depends on the scenario, because removeif returns a Boolean and filter is a filterintermediate operation, needterminal operationFinally, the flow is processed. If you only delete / filter, removeif will be faster.

Example:

public static void main(String[] args) {
        List list = new ArrayList(Arrays.asList(1,2,3,4,5));
        long last = System.currentTimeMillis();
        list.removeIf(a -> a.equals(2));
        System.out.println(System.currentTimeMillis() - last);//37~38
    }
public static void main(String[] args) {
        List list = new ArrayList(Arrays.asList(1,2,3,4,5));
        long last = System.currentTimeMillis();
        list.stream().filter(a -> !a.equals(2)).collect(Collectors.toList());
        System.out.println(System.currentTimeMillis() - last);//41~44
    }

Let’s look at the source code implementation:

Removeif is the default method of the collection interface (new in Java 8). The underlying implementation is to obtain the iterator to iterate over each element to meet the conditionsremove()Method is deleted and returns true until the end of the iteration. Elements that do not meet the conditions after the iteration return false. If multiple intermediate flows participate, filter is recommended for convenience.

default boolean removeIf(Predicate super E> filter) {
  //Determine whether it is null
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator each = iterator();
        while (each.hasNext()) {
         //If a runtime exception or error occurs in the iteration, the predicate is forwarded to the caller
            if (filter.test(each.next())) {
             //The bottom layer of remove calls the system.arraycopy method, which is a native method written in C + +. It operates on pointers, which is relatively fast
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

Each time the filter generates a new statelessop, that is, a new stream. The conditions are constantly matched through opwrapsink. When it is false, mark this stream element for filtering

@Override
    public final Stream filter(Predicate super P_OUT> predicate) {
     //Determine whether it is null
        Objects.requireNonNull(predicate);
        //Attach stateless intermediate operations to an existing flow to construct a new flow. StreamOpFlag.NOT_ Sized indicates the bit value to be cleared
        return new StatelessOp(this, StreamShape.REFERENCE,
                                     StreamOpFlag.NOT_SIZED) {
            @Override
            Sink opWrapSink(int flags, Sink sink) {
                return new Sink.ChainedReference(sink) {
                    @Override
                    public void begin(long size) {
                        downstream.begin(-1);
                    }

                    @Override
                    public void accept(P_OUT u) {
                        if (predicate.test(u))
                            downstream.accept(u);
                    }
                };
            }
        };
    }
//Bit value to clear
static final int NOT_SIZED = SIZED.clear;

SIZED(3,
          set(Type.SPLITERATOR).set(Type.STREAM).clear(Type.OP)),

Source: blog.csdn.net/butterfly_ resting/article/details/100045181

Recent hot article recommendations:

1.1000 + java interview questions and answers (2021 latest version)

2.Stop playing if / else on the full screen. Try the strategy mode. It’s really fragrant!!

3.what the fuck! What is the new syntax of XX ≠ null in Java?

4.Spring boot 2.5 heavy release, dark mode is too explosive!

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don’t forget to like + forward!

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]