简体   繁体   中英

Convert java List to object using collection -Stream

From the method List> method() i get the output like this with 3 elements

[123456, 10, 03-JAN-16]
[956233, 20, 03-JAN-16]
[254656, 30, 03-JAN-16]
[455556, 40, 04-JAN-16]
[548566, 50, 03-JAN-16]
[215663, 60, 03-JAN-16]

I need to store the above result in a pojo class name 'ClassName' which has the following columns col1, col2 and col3, So I try to run the following code as

public void method() {
    try {
        List<List<String>> list = testDAO.methodName();
        List<ClassName> className= new ArrayList<ClassName>();
        for (Iterator<List<String>> iterator = list.iterator(); iterator.hasNext();) {
            List<String> list2 = (List<String>) iterator.next();
            int i = 0;
            ClassName className= new ClassName ();
            for (Iterator<String> iterator2 = list2.iterator(); iterator2.hasNext();) {
                String string = (String) iterator2.next();
                /* System.out.println(string); */
                if (i == 0)
                    className.setCol1(string);
                else if (i == 1)
                    className.setCol2(Long.parseLong(string));
                else if (i == 2)
                    className.setCol3(string);
                i++;

            }
            odhs.add(className);

            System.out.println(className);
            // System.out.println(className.col2());
            // System.out.println(className.col3());
        }
        // System.out.println("Total size: "+ odhs.size());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But i got the output as

com.project.model.ClassName@61af1510
com.project.model.ClassName@37af1f93
com.project.model.ClassName@778d82e9
com.project.model.ClassName@408e96d9
com.project.model.ClassName@59901c4d
com.project.model.ClassName@168cd36b
com.project.model.ClassName@d8d9199
com.project.model.ClassName@3901f6af

Please provide a solution to save the datas in the POJO class 'ClassName'

您的类Odh必须重写toString方法。

Override Odh's toString method.

Assuming the names of your parameters are dist_id , pv and post_date and all are of String types

@Override
public String toString(){
   return getClass().getSimpleName() + "[dist_id=" + dist_id + ", pv=" + pv + ", post_date=" + post_date + "]";
}

That would allow you to print

Odh[dist_id=123456, pv=10, post_date=03-JAN-16]

On your Odh class you have to override toString method.

@Override
    public String toString ( )
    {
        return "Odh [firstAttribute=" + firstAttribute + ", secondAttribute=" + secondAttribute + "]";
    }

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