Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize Java Collection List a Map inside

Tags:

java

@Entity

public class SalesT {

    @Id
    @GeneratedValue
    private int id;

    @OneToOne
    private Customer customer;

    @OneToMany(targetEntity = Product.class)
    private List< Map<Product,Integer> > listProduct;// I want to intialize this

    public SalesT() {
    }

    public SalesT(Customer customer, List<Map<Product, Integer>> product) {
        this.customer = customer;
        this.listProduct = product;
    }
}

I want to Initialize List< Map < Product,Integer>> listProduct attribute of the SalesT Class, How do I initialize it?. I tried Like this

List<Map <Product, Integer>> listProduct = new ArrayList <HashMap <Product, Integer>>();

but it is not working.

Thank you.

like image 516
Gebrekiros Avatar asked Dec 11 '25 15:12

Gebrekiros


1 Answers

If you're using JDK 7, you can simply do,

listProduct = new ArrayList<>();

If JDK < 7,

listProduct = new ArrayList<Map<Product, Integer>>();

You can add maps to above list as follows.

Map<Product,Integer> productMap = new HashMap<Product, Integer>();
productMap.put(new Product(), 1);
productMap.put(new Product(), 2);

listProduct.add(productMap);
like image 109
TheKojuEffect Avatar answered Dec 14 '25 05:12

TheKojuEffect