Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set object value using List<Object> to a model class in java?

how do add each property value in my model using List? Here is what i do

here is my object : Item.java

public class Item {

    private String code;

    private String name;

    private Integer qty;

    // skip the getter setter
}

here is how i want to add the value from another class

List<Item> sBarang = new ArrayList<Item>();
sBarang.add("");

How do I add each property value my Item.java?

What I can do is something like this :

Item mItem = new Item();
mItem .setCode("101");
mItem .setName("Hammer");
mItem .setQty(10);
like image 873
Ke Vin Avatar asked Dec 25 '14 03:12

Ke Vin


People also ask

How do you assign object to object in Java?

First, define a class with any name 'SampleClass' and define a constructor method. The constructor will always have the same name as the class name and it does not have a return type. Constructors are used to instantiating variables of the class. Now, using the constructors we can assign values.

How do you convert an object list to a single object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.

How do you assign an object to a list in Java?

You can get the object at an index using obj = listName. get(index) and set the object at an index using listName. set(index,obj) . import java.

Can we convert list to object in Java?

Core Java bootcamp program with Hands on practiceA list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);


2 Answers

Unless I'm missing something you just need to add your mItem to your List. Like

Item mItem = new Item(); // <-- instantiate a new Item.
mItem.setCode("101");
mItem.setName("Hammer");
mItem.setQty(10);
sBarang.add(mItem); // <-- add it to your List<Item>.

You could also create a new Item constructor that looks something like

public Item(String code, String name, Integer qty) {
    this.code = code;
    this.name = name;
    this.qty = qty;
}

and then use a single line add like

sBarang.add(new Item("101", "Hammer", 10)); 
like image 191
Elliott Frisch Avatar answered Oct 04 '22 11:10

Elliott Frisch


Make a constructor for your convenience.

public class Item {
    public Item(String code, String name, int qty){
        this.code=code;
        this.name=name;
        this.qty=qty;
    }
    private String code;

    private String name;

    private Integer qty;

    //skip the getter setter
}

Since then, you can add new "Item" object easily by

sBarang.add(new Item("101","Hammer",10));
like image 43
Patrick Chan Avatar answered Oct 04 '22 10:10

Patrick Chan