This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

directory

  • The problem
  • To solve

The problem

Question: How to convert a List to an int[] array?

Stackoverflow address: stackoverflow.com/questions/9…

General practice:

int[] toIntArray(List<Integer> list){
    int[] ret = new int[list.size()];
    for(int i = 0; i < ret.length; i++) ret[i] = list.get(i);return ret;
}
Copy the code

To solve

Some people believe that the above conventional approach is the best approach, and it has received a lot of approval.

However, it was later pointed out that there is a more convenient way to do this if you are using Java 8.

The specific coding is as follows:

int[] array = list.stream().mapToInt(i->i).toArray();
Copy the code

Or use

int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Copy the code

There are three reasons for this.

ToArray () returns an array of Object[] objects, which is not what we want.

An Integer array is not the same as an int array, so we need to convert it to a real int array.

Int #intValue (); int #intValue ();

mapToInt( (Integer i) -> i.intValue() )  
Copy the code

In fact, there is a simpler method, we can write as follows:

mapToInt((Integer i)->i)
Copy the code

Also, since the compiler can infer that I is an Integer type and that List#stream () returns stream, we can skip this step and get a simpler method:

 mapToInt(i -> i)
Copy the code