简体   繁体   中英

Setting values in an ArrayList with multiple objects

Exaustive example are given on how to set a value in a 1D ArrayList, but could not find one on how to set a value of the ArrayList object after computations have been done from the dataset. The image shows a null value in test and this is the value to be updated after computations. Any hints?

带对象的 ArrayList

If I understand you correctly, you have a List<> of objects on which you want to do computations. This is easily done with Streams.

        MyObject object1 = new MyObject(new Date(), "", "", null);
        MyObject object2 = new MyObject(new Date(), "", "", null);

        // for example purposes, I'm creating a List<> with two objects in it
        List<MyObject> myList = new ArrayList<>(); 
        myList.add(object1);
        myList.add(object2);
        
        myList = myList.stream()
                .map(myObject -> {
                    String result = "do some computations which result in a value to set";
                    myObject.setTest(result);
                    return myObject;
                })
                .collect(Collectors.toList());

// if you were to look into your objects, you'll see that the null-value is replaced
private class MyObject {

        private Date date;
        private String vwapspy;
        private String vwapgdx;
        private String test;

// constructor

// getters and setters

}

Your main goal would be to update your variable. Within the .map() function of the Stream, you can easily place any logic you want.

Ofcourse, Streams are only available since Java 8. Such logic as in the example can be done with simple loops as well. Look into some tutorials if I'm not clearly addressing your use-case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM