Sample
unknown
plain_text
a year ago
3.1 kB
2
Indexable
Never
package com.example.collectionframework.demo; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class ListDemo { public static void main(String[] args) { // rawListDemo(); ArraylistsDemo(); linkedListDemo(); } // removals and insertions private static void linkedListDemo() { List<String> linkedList = new LinkedList<>(); linkedList.add("hello"); linkedList.add(1,"world"); linkedList.add(2,"from java"); System.out.println(linkedList); linkedList.remove("hello"); String[] stringsArray = linkedList.toArray(new String[0]); System.out.println(stringsArray); linkedList.sort(Comparator.naturalOrder()); } // accessing faster private static void ArraylistsDemo() { // Concrete List with type // String, Integer, Double, Float, Boolean, Course List<String> strings = new ArrayList<String>(); List<String> stringList = new ArrayList<>(); strings.add("hello"); strings.add("world"); strings.add(null); // strings.add(1); strings.add(1, "java"); strings.addAll(List.of("l1", "l2", "l3", "l4")); strings.addAll(4, Arrays.asList("m1", "m2", null, "m3", null)); int listSize = strings.size(); String s = strings.get(0); // 1st way for(int i=0;i<strings.size();i++) { System.out.print(strings.get(i)+" "); // continue and break } System.out.println(); // 2nd way strings.forEach(str -> { System.out.println(str); // continue and break are not supported }); // 3rd way for(String str : strings){ // continue not supported, break is supported } strings.removeIf(s1 -> Objects.isNull(s1)); // delete basis condition strings.remove("l1"); strings.remove(3); // streaming elements System.out.println(strings.stream().filter(s1 -> s1.length() > 4).collect(Collectors.toList())); // remove in bulk strings.removeAll(Arrays.asList("l1", "l2", "l3")); System.out.println("strings after removal of l1, and l2" + strings); strings.retainAll(Arrays.asList("m1", "m2", "m3")); System.out.println("strings after retain of m1, and m2" + strings); // check if element exists boolean m2Exists = strings.contains("m2"); int m2Index = strings.indexOf("m2"); // if not exists it gives u -1 // clear the list strings.clear(); } private static void rawListDemo() { // Raw List List list = new ArrayList(); list.add(10); list.add("hello"); list.add(true); System.out.println(list); Integer i1 = (Integer) list.get(0); System.out.println(i1); String str = (String) list.get(0); System.out.println(str); } }