List processing of data in java

        When it comes to List, the most commonly used and most familiar one is List traversal. Of course, there are other data processing for List, addition, deletion, modification, and data transformation. It can be said that almost every programmer is more or less using List for data processing or optimization in order to achieve their own goals. Expected data information. I have some time today, so I simply organized the List.

1. List traversal

In summary, there are the following:

1.foreach

 List<String> list = new ArrayList<>();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        list.add("dd");
        list.add("ac");

        for (String str:list) {
            //to do sth
        }

I won’t say more about it, everyone can understand it.

2.holes

 List<String> list = new ArrayList<>();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        list.add("dd");
        list.add("ac");

        for (int i = 0,j=list.size(); i < j; i++) {
            // to do sth
        }

This interjection, when you generally use fori, is like this:

for (int i = 0; i < list.size(); i++) {
            // to do sth
        }

Of course there is nothing wrong with writing this way, but every time you traverse, you will get the size() of the list, which has a certain impact on performance. Of course, this is minimal, but if it is used frequently and the amount of data is large, it is not recommended to use this way, it will increase time consuming. If you assign list.size() to j in advance, you don’t need to fetch the size() of the list afterwards. At the same time, j is in the method area, and only one assignment is performed. After that, it can be used in the loop forever. The performance is undoubted. It will improve so much.

3.iterator

Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
           // to do sth
        }

Iterator traversal should be familiar to everyone. This is generally used to delete a certain data in the List. Iterator.remove is used. Deleting during the traversal process has no effect on the List.

4、stream

list.stream().forEach(str->{
            //to do sth
        });

stream() is a newly added stream of JDK1.8 to process some data, which has the following characteristics:

  • Based on set or sequence
  • The stream does not store values, nor can it be reused, and the data is manipulated by way of pipelines
  • Each operation is functional, and the operation on the stream will not affect the source data
  • Most operations (sorting, mapping, filtering, etc.) can be delayed

 Of course, after stream(), you can filter (filter), sort (groupingBy), generate new lists, etc. I won't talk about it here. If you are interested, you can see the application of JDK1.8's new feature lamada expression

Two, List deletes data

As for the deletion of the list, everyone should have a certain understanding. You must not delete while traversing, like this

for (String str:list) {
            if(str.equals("...")){
                list.remove(str);
            }
        }

It will happen, so we try not to mess things up. The main deletion methods are as follows:

1. Use iterator to delete

This is to traverse the data, and then use iterator.remove() to remove the eligible data, which is currently the most widely used operation. You can refer to the iterator traversal above, so I won't talk about it here.

2. Create a new List, collect all the data that needs to be deleted, and then remove all.

  List<String> deleteList= new ArrayList<>();
        for (String str:list) {
            if(str.equals("...")){
                deleteList.add(str);
            }
        }
        list.removeAll(deleteList);

3. Create a new list to traverse, and delete the original list.

List<String> list = new ArrayList<>();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        list.add("dd");
        list.add("ac");

        List<String> copyList= new ArrayList<>();
        copyList.addAll(list);
        for (int i = copyList.size()-1; i >=0 ; i--) {
            String s = copyList.get(i);
            if(s.equals("...")){
                list.remove(i);
            }
        }

4. Use Lamada

        List<String> newList = list.stream().filter(s -> (!s.equals("..."))).collect(Collectors.toList());

Also, please note that you can’t remove empty data directly

list.removeAll(null);

Something will happen, look at the picture below:

removeAll does not allow the input parameter to be empty, so it is no problem to write:
list.removeAll(Collections.singleton(null));

 Three, add/insert

The longest use for adding is add(), but sometimes it needs to be inserted. But this is not too difficult, just mention it briefly.

1. Add at the end of List, list.add();

2. List increase collection, list.addAll();

3. Add the first part of List, list.add(0,str);

4. The list is inserted into multiple positions and multiple pieces of data. In this case, it needs to be traversed. When inserting, the size of the List is changing. Therefore, the first is to clone a list for traversal, the original list is added for operation, and the second is to traverse. When traversing in reverse order, this ensures that the value of i is always consistent with the original list, because reverse insertion has no effect on the value in front of i

Four, List and Array

As you all know, the bottom layer of List is Array, and the reason why the length of List is not fixed is that List dynamically expands as needed. Usually when we are coding code, many places will involve the conversion of List and Array, here is also a brief mention.

1.list to array

A two-step strategy~

 String[] strArray = new String[list.size()];
 String[] array = list.toArray(strArray);

 2.array to list

List<String> strings = Arrays.asList(array);

3. Sorting problem

Array:

 Arrays.sort(array);

List:

        Collections.sort(list);
        //或
        list.sort(String::compareTo);  //按照字节码排序

This sorting implements a compareTo method, programmers can customize according to their needs, and then sort, the following two methods are also more commonly used

 Collections.shuffle(list);   //打乱
 Collections.reverse(list);   //倒序

List (mainly ArrayList) commonly used is probably these, if you have any questions, you can discuss it together~

Guess you like

Origin blog.csdn.net/zsah2011/article/details/90312058