The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java Collection 移除元素的几种方式

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.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4453.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

【最新更新】ZN7号_微盘wp二开版带余额宝功能时间盘黄金期货数字火币交易+完整数据+k线正常
[Latest update] ZN No. 7_microdisk wp second edition with balance treasure function Time disk gold futures digital hot coin trading + complete data +k line normal
Someone bought it 10 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish