Convert List to Array using java8

Third-party libraries need to be called during development. The input parameters of some APIs are required to be a double[] array. The program calculates a double[] as the result of the return value according to the user's input on the page, and then calls this API.

It is often impossible to know the size of the double[] array in advance, so you cannot directly define a double[] variable. You can only use List to put the data into the List first, and then convert it into a double[] array. This is very simple, a for loop will do it, but using the stream feature of java 8 can make the code more elegant. Here is an example from my program:

 

[java] view plain copy
 
print ?
  1. List<Double> factorValueList = new ArrayList<>();  
  2. for (Integer defId : input.getCohortDefIds()) {  
  3.     for (double d : calcVarValues(defId, factorVar)) {  
  4.         factorValueList.add(d);  
  5.     }  
  6. }  
  7. double[] factorVarValues = factorValueList.stream().mapToDouble(Double::doubleValue).toArray();  
List<Double> factorValueList = new ArrayList<>();
for (Integer defId : input.getCohortDefIds()) {
	for (double d : calcVarValues(defId, factorVar)) {
		factorValueList.add(d);
	}
}
double[] factorVarValues = factorValueList.stream().mapToDouble(Double::doubleValue).toArray();


List itself has an API, which is toArray() with parameters, but in some cases, the Array compiles without any problem after the transformation, and an error is reported at runtime. I forgot the specific error, and I will update the article next time I find it.

To be on the safe side, using streams is the most reliable and the code looks good.

 

Convert array to List

1. Use the Collector collector in Stream, code:

 

[java] view plain copy
 
print ?
  1. String[] arrays = new String[]{"a""b""c"};  
  2. List<String> listStrings = Stream.of(arrays).collector(Collectors.toList());  
        String[] arrays = new String[]{"a", "b", "c"};
        List<String> listStrings = Stream.of(arrays).collector(Collectors.toList());


2. Use the asList() method in the java.util.Arrays utility class (this is not new in Java8):

 

 

[java] view plain copy
 
print ?
  1. String[] arrays = new String[]{"a""b""c"};  
  2. List<String> listStrings = Arrays.asList(arrays);  
        String[] arrays = new String[]{"a", "b", "c"};
        List<String> listStrings = Arrays.asList(arrays);


Convert List to Array

1. Using Stream:

 

[java] view plain copy
 
print ?
  1. String[] ss = listStrings.stream().toArray(String[]::new);  
String[] ss = listStrings.stream().toArray(String[]::new);

2. Use the toArray() method in List

 

[java] view plain copy
 
print ?
  1. String[] sss = listStrings.toArray(new String[listStrings.size()]); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326260961&siteId=291194637