简体   繁体   中英

Convert List of Objects to List of String with filter using Java Streams

To fetch all the estd codes value from a list of Objects, where iEflag value is "E". Tried this, but not working.

List<String> estdCodeList = applEstdList.stream()
                    .map(StdCode::getEstdCode)
                    .filter(x -> x.getiEflag().equals("E"))
                    .collect(Collectors.toList());

where applEstdList , list of objects of type StdCode .

public class StdCode   implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String applnCode;
    private String estdCode;
    private String iEflag;

}

This code I was trying to convert using Java Streams. Does using Stream here have any performance benefits?

List<String> iEflagIsE = new ArrayList<String>();
                List<String> iEflagIsNotE = new ArrayList<String>();

                //Creating the respective exclusion inclusion list
                for(ApplicationEstCode applnList :applEstList){
                    if(applnList.getiEflag().equals("E")){
                        iEflagIsE.add(applnList.getEstCode());
                    }else{
                        iEflagIsNotE.add(applnList.getEstCode());
                    }
                }

You are missing another map ping possibly as:

List<String> stdCodeList = applEstdList.stream()
                .map(StdCode::getStdCode)
                .map(a -> a.getiEflag())
                .filter(x -> x.equals("E"))
                .collect(Collectors.toList());

or combine the map operations to:

List<String> stdCodeList = applEstdList.stream()
                .map(applEstd -> applEstd.getStdCode().getiEflag())
                .filter(iEflag -> iEflag.equals("E"))
                .collect(Collectors.toList());

Problem is this line:

.map(StdCode::getEstdCode)

converts your source StdCode type collection to a collection of estdCode strings, and then this output is passed to next filter method. I think it should complain an error like the method doesn't exists because you are feeding it a collection of String objects that don't have the `getiEflag()) method.

If you change the order of these two methods:

List<String> estdCodeList = applEstdList.stream()
                    .filter(x -> x.getiEflag().equals("E"))
                    .map(StdCode::getEstdCode)
                    .collect(Collectors.toList());

that should work.

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