Is there a better alternative to List <T> listings than calling Arrays.asList?

Is there a better alternative to using Arrays.asList as a list initializer? It is troubling that this question is verbose and includes an extraneous class and method.

List<Double> myList = new ArrayList<Double>(Arrays.asList(3.01d, 4.02d, 5.03d)); 

Edit: This question relates to mass initialization, which usually has more than three values ​​shown in the example.

+6
source share
6 answers

If you know that you no longer need to add anything to the list, you can simply do

 List<Double> myList = Arrays.asList(3.01d, 4.02d, 5.03d); 

I am sure that the list returned from Arrays.asList can be changed, but only that you can change the elements that are, you cannot add new elements to it.

+5
source

Use guava ,

 List<Double> myList = Lists.newArrayList(3.01d, 4.02d, 5.03d)); 
+3
source

Another option would be an anonymous inner class:

 List<Double> myList = new ArrayList() { { add(3.01d); add(4.02d); add(5.03d); } }; 
+1
source

Yes, you can do it like this:

 List<Double> myList = Arrays.asList(new Double[]{3.01d, 4.02d, 5.03d}); // or List<Double> myList = Arrays.asList(3.01d, 4.02d, 5.03d); 
+1
source

Does not correspond to the question 100%, but adds this answer if the desire to establish a list is to immediately do something with the values ​​in it, and not just create an instance of List for just making only an instance.

With Java 8, you can use Stream.of(T... values) , then manipulate the password through the stream API to get the results you would like to get from the list of values.

For example, to get the maximum value of a series of values ​​...

int maxValue = Stream.of(10, 5, 25).max(Integer::compareTo).get();

The above example is also useful if you want to use a function like Math.max(#,#) , but more than two arguments are required for processing.

0
source

Since java 9 you can use the List.of factory method:

 static <E> List<E> of​(E... elements) 

Returns an immutable list containing an arbitrary number of elements.

Or use guava:

 public static <E> ImmutableList<E> of(E e1, E e2,...) 

Returns an immutable list containing the specified elements, in order.

0
source

Source: https://habr.com/ru/post/893925/


All Articles