Loading...
Sunday, February 18, 2018

Collections - Factory method for immutable Set using String java 9



ImmutableSet.java
package com.java9r;

import java.util.*;

public class ImmutableSet {

public static void main(String[] args) {

System.out.println("Products List");
try {
Set<String> products = Set.of("Product 1", "Product 2", "Product 3", "Product 4", "Product 5", "Product 5");
products.forEach(product -> {
System.out.print(product + "\n");

});

} catch (Exception e) {
e.printStackTrace();
}
}
}



Exception

Names List
Exception in thread "main" java.lang.IllegalArgumentException: duplicate element: Product 5
at java.base/java.util.ImmutableCollections$SetN.<init>(Unknown Source)
at java.base/java.util.Set.of(Unknown Source)
at com.java9r.ImmutableSet.main(ImmutableSet.java:10)




ImmutableSet.java
package com.java9r;

import java.util.*;

public class ImmutableSet {

public static void main(String[] args) {

System.out.println("Products List");
try {
Set<String> products = Set.of("Product 1", "Product 2", "Product 3", "Product 4", "Product 5");
products.forEach(product -> {
System.out.print(product + "\n");

});

} catch (Exception e) {
e.printStackTrace();
}
}
}


Output

Names List
Product 5
Product 2
Product 1
Product 4
Product 3

0 comments:

Post a Comment

 
TOP