简体   繁体   中英

Value insertion into list using JAVA 8

public static void main(String[] args) {

    List<Long> list = new ArrayList<>();

    for (long i = 1; i < 100000000; i++) {
        list.add(i);
    }



}

this loop taking too long to insert values into the list is there any features in JAVA 8, using that the same task will perform in a minimal time.

If it's not mandatory that the list be an ArrayList :

    Long[] array = new Long[100_000_000];
    Arrays.parallelSetAll(array, Long::valueOf);
    List<Long> list = Arrays.asList(array);

I have not done any time measurements. The list will be modifiable in the sense that you can set values, but it has fixed size, there is no adding or removing.

If you do need a variable-size list, you may try:

    List<Long> list = new ArrayList(Arrays.asList(array));

It somewhat defies the idea of exploiting parallel execution, though, and I am no longer sure about how the speed would compare to what you have already got.

Edit: If the list doesn't need to be modifiable at all, make your own “list” implementation that doesn't store any actual data and calculates the value each time an element is asked for. Then initialization will take no time. You can subclass AbstractList for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM