
1. preface
An action set is a Java Something programmers repeat almost every day. Today we will study the results from Java Collection Method to delete elements in. I built a simple collection that we used as an example to explore.
List<String> servers = new ArrayList<>();
servers.add("Felordcn");
servers.add("Tomcat");
servers.add("Jetty");
servers.add("Undertow");
servers.add("Resin");
2. A for loop does not necessarily remove elements from the collection
Let's use traditional foreach
cyclic removal F
Fake server at the beginning, but you will find that this operation triggers ConcurrentModificationException
abnormal.
//Don't use wrong demonstrations
for (String server : servers) {
if (server.startsWith("F")) {
servers.remove(server);
}
}
Can't a for loop remove elements? Of course not! It is still possible if we can determine the index of the element that needs to be removed.
//This method is feasible
for (int i = 0; i < servers.size(); i++) {
if (servers.get(i).startsWith("F")) {
servers.remove(i);
}
}
But I have only demonstrated this method so far ArrayList
, other types are not strictly tested and are left to you to explore for yourself.
3. Iterator can delete elements in a collection
In the traditional way, we use Iterator
Elements can be guaranteed to be deleted:
Iterator<String> iterator = servers.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.startsWith("F")) {
iterator.remove();
}
}
4. Disadvantages of iterating and deleting elements
- We need to iterate over every element of the collection and assert them, even if you delete one element.
- Although we can delete specific elements iteratively, the operation is cumbersome and has potential
ConcurrentModificationException
abnormal. - Depending on the data structure, the time complexity of deleting elements also varies greatly. For example, array structures
ArrayList
The speed of deleting elements is not as fast as the linked list structure.LinkedList
。
5. New collection element deletion operation
Java 8 Provides new collection operations API and Stream to help us solve this problem. I have already introduced it in previous articles Java 8 Stream API, if you are interested, you can go and have a look.
5.1 Collection.removeIf()
new Collection
Api removeIf(Predicate<? super E> filter)
。the Api Provides a more concise way to use Predicate
(Assertion) Method to delete elements, so that we can more succinctly implement the initial requirements:
servers.removeIf(s-> s.startsWith("F"));
At the same time, according to tests,ArrayList
and LinkedList
The performance is close. This method is generally recommended for operation.
5.2 Stream implements removing elements
Unlike all the above removal operations, nothing changes Stream
Source, we just use Stream
Api Operate a copy of the data source. followed Data source-intermediate operation-induction termination
life cycle. Let's take a look at using Stream
How to achieve our intentions.
5.2.1 Implementation through filter assertion
we can use Stream
the filter
Assertion.filter
Assertions will gather the flow elements that match the assertion into a new flow and then summarize them, so we can write this:
//The difference is that the assertion in this method is a negation operation.
List<String> newServers = servers.stream().filter(s -> ! s.startsWith("F")).collect(Collectors.toList());
As mentioned above, this advantage will not affect the original data, and what is generated is a copy. The downside is that there may be memory usage issues.
5.2.2 Summarize by Collectors.partitioningBy
Although this method can meet the needs, I feel a bit opportunistic.Collectors.partitioningBy()
The original intention of the method is to make binary classification. This method summarizes elements in the flow that match assertions and those that do not match assertions into two key
respectively true
and false
the Map
In, we can classify consistent and inconsistent sets of elements. The implementation is as follows:
Map<Boolean, List<String>> f = servers.stream().collect(Collectors.partitioningBy(s -> ! s.startsWith("F")));
List<String> trues = f.get(Boolean.TRUE);
System.out.println("Those that do not begin with F: " + trues);
List<String> falses = f.get(Boolean.FALSE);
System.out.println("Beginning with F: " + falses);
Generally, this method is not recommended for use in this scenario and does not meet this requirement. Api design intention.
6. summary
Today we studied some of the results Collections
Methods and considerations for deleting elements in. I don't know if you have any other way to implement it, but you might as well use the public account:Felordcn Tell me.
Comments0