Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the ways to initialize List collections in Java

Shulou Source: shulou.com Published: 2022-06-03 15:22:25 09月18日 Update

Editor to share with you what are the ways to initialize the List collection in Java, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

List is a common collection in development. Here are several ways to initialize List.

Conventional mode

List list = new ArrayList (); list.add ("1"); list.add ("2"); list.add ("3"); System.out.println ("getList1:" + list)

Output

GetList1: [1, 2, 3]

Arrays utility class

/ the generated list immutable List list = Arrays.asList ("1", "2", "3"); System.out.println ("getList2:" + list); / / if you need to wrap List numbers = new ArrayList (Arrays.asList ("1", "2", "3")) in ArrayList if you want to change it; numbers.add ("4"); System.out.println ("numbers:" + numbers)

Output

GetList2: [1, 2, 3] numbers: [1, 2, 3, 4]

Collections utility class

/ the generated list immutable List list = Collections.nCopies (3, "1"); System.out.println ("getList3:" + list); / / if you need to wrap it in ArrayList, List dogs = new ArrayList (Collections.nCopies (3, "dog"); dogs.add ("dog"); System.out.println ("dogs:" + dogs)

Output

GetList3: [1, 1, 1] dogs: [dog, dog]

Lists utility class

List list = Lists.newArrayList ("1", "2", "3"); System.out.println ("getList4:" + list)

Output

GetList4: [1, 2, 3]

Anonymous inner class

List list = new ArrayList () {{add ("1"); add ("2"); add ("3");}}; System.out.println ("getList5:" + list)

Output

GetList5: [1, 2, 3]

ImmutableList

List list = ImmutableList.of ("1", "2", "3"); System.out.println ("getList6:" + list)

Output

GetList6: [1, 2, 3]

Java8 Stream

List list = Stream.of ("1", "2", "3"). System.out.println (Collectors.toList ()); System.out.println ("getList7:" + list)

Output

GetList7: [1, 2, 3]

Java9 List.of

List list = List.of {"1", "2", "3"}; System.out.println ("getList8:" + list)

Output

GetList8: [1, 2, 3] the above is all the contents of the article "what are the ways to initialize List collections in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Output mode variable tools articles content packaging generation not much most commonly used conventional is in more knowledge industry information information channels channels references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker vpn Apple Microsoft