List and Set in Java
List and Set are common collections in Java. They are used to contain items that have the same data type. The difference is List allow contain duplication of items while Set is not allowed.
Code example:
String animals= "cat,dog,buffalo,cat,pig,dog";
String str[] = animals.split(",");
List<String> animalList = Arrays.asList(str);
animalList.stream().forEach(item -> System.out.print(item + ", "));
System.out.println(); // break down line
Set<String> animalSet = new HashSet<>(animalList);
animalSet.stream().forEach(item -> System.out.print(item + ", "));
Result:
cat, dog, buffalo, cat, pig, dog,
cat, buffalo, dog, pig,
NOTEs Errors:
1. Exception in thread “main” java.lang.UnsupportedOperationException: remove
Run the following code below to get the error:
String animals= "cat,dog,buffalo,cat,pig,dog";
String str[] = animals.split(",");
List<String> animalList = Arrays.asList(str);
animalList.stream().forEach(item -> System.out.print(item + ", "));
animalList.remove("cat");
animalList.stream().forEach(item -> System.out.print(item + ", "));
Root cause: Immutable collection.
When instantiating collection by Arrays.asList or Set.of, these constructors produce immutable collections, which means we cannot modify items in the result (add, remove, update).
Solution: Init collection following:
List<String> animalList = new ArrayList<>(Arrays.asList(str));
2. Exception in thread “main” java.lang.IllegalArgumentException: duplicate element: …
Run the following code below to get the error:
String animals= "cat,dog,buffalo,cat,pig,dog";
String str[] = animals.split(",");
Set<String> animalSet = Set.of(str); // str array contain duplication items
animalSet.stream().forEach(item -> System.out.print(item + ", "));
Root cause: str array contain duplication items
Solution: Init collection following:
Set<String> animalSet = new HashSet<>(Arrays.asList(str));
Happy Coding..!!! <3