Searching...
Sunday, February 18, 2018

Collections - Factory method for immutable Set using Bean java 9

February 18, 2018

ImmutableSet.java

package com.java9r;

import java.util.*;

public class ImmutableSet {

public static void main(String[] args) {

try {

System.out.println("Products List");
Set<Product> products = Set.of(new Product("100", "Product 1", 10), new Product("101", "Product 2", 20),
new Product("102", "Product 3", 30), new Product("103", "Product 4", 40),
new Product("104", "Product 5", 50));
products.forEach(p -> {
System.out.println("Id: " + p.getId());
System.out.println("Name: " + p.getName());
System.out.println("Price: " + p.getPrice());
System.out.println("=========================");
});

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


Product.java

 package com.java9r;

public class Product {

private String id;
private String name;
private double price;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public Product(String id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}


}


Output



Products List

=========================

Id: 102

Name: Product 3

Price: 30.0

=========================

Id: 103

Name: Product 4

Price: 40.0

=========================

Id: 104

Name: Product 5

Price: 50.0

=========================

Id: 101

Name: Product 2

Price: 20.0

=========================

Id: 100

Name: Product 1

Price: 10.0

=========================




0 comments:

Post a Comment

ads2