Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Initialize Immutable List
*/
// 1. Java 8 or before
List<String> list1 = Arrays.asList("foo", "bar", "baz");
// 2. Java 9 or later
List<String> list3 = List.of("foo", "bar", "baz");
// 3. Using Streams
List<String> list2 = Stream.of("foo", "bar", "baz").collect(Collectors.toList());
/**
* Initialize Mutable ArrayList & LinkedList
*/
// 1. Java 8 or before
ArrayList<String> arraylist1 = new ArrayList<>(Arrays.asList("foo", "bar", "baz"));
LinkedList<String> linkedlist1 = new LinkedList<>(Arrays.asList("foo", "bar", "baz"));
// 2. Java 9 or later
ArrayList<String> arraylist2 = new ArrayList<>(List.of("foo", "bar", "baz"));
LinkedList<String> linkedlist2 = new LinkedList<>(List.of("foo", "bar", "baz"));
// 3. Using Streams
ArrayList<String> arraylist3 = Stream.of("foo", "bar", "baz").collect(Collectors.toCollection(ArrayList::new));
LinkedList<String> linkedlist3 = Stream.of("foo", "bar", "baz").collect(Collectors.toCollection(LinkedList::new));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment