Home > front end >  How to add values to list from Object using stream
How to add values to list from Object using stream

Time:10-08

I have a Object with multiple properties and I want to add multiple properties to same list

I was able to add one property couldn't find a way to add other property.

Can we do that if yes how ?

List<MyObject> myObject = new ArrayList<>();

I have some values in the object  here 

List<Long> Ids  = myObject .stream().map(MyObject::getJobId).collect(Collectors.toList());

here I want to add one more property from same MyObject object getTestId to the list is there a way that I can add with in the same above statement ?

CodePudding user response:

Create two lists using the streams then combine them in the end, map can only return one value either getJobId or getTestId, so you can't do it in the same iteration.

    List<Long> JobIds = myObject.stream().map(myObj::getJobId).collect(Collectors.toList());
    List<Long> TestIds = myObject.stream().map(myObj::getTestId).collect(Collectors.toList());
    List<Long> Ids = Stream.concat(JobIds.stream(), TestIds.stream()).collect(Collectors.toList());

CodePudding user response:

If you want a list containing the jobIds and the testIds then you can use something like this:

List<Long> ids = new ArrayList<>();
myObject.stream().forEach(o -> { 
    ids.add(o.getJobId());
    ids.add(o.getTestId()); 
});

CodePudding user response:

In .map operation the object should be mapped to a list/stream of required ids and then apply flatMap:

List<Long> ids = myObject
        .stream()
        .map(mo -> Arrays.asList(mo.getId(), mo.getTestId()))
        .flatMap(List::stream)
        .collect(Collectors.toList());

or (same as Holger's comment)

List<Long> ids = myObject
        .stream()
        .flatMap(mo -> Stream.of(mo.getId(), mo.getTestId()))
        .collect(Collectors.toList());

If the ids should be followed by testIds, the streams may be concatenated:

List<Long> ids = Stream.concat(
    myObject.stream().map(MyObject::getId),
    myObject.stream().map(MyObject::getTestId)
)
.collect(Collectors.toList());

If more than two properties should be listed one after another, Stream.of flatMap should be used:

List<Long> ids = Stream.of(
    myObject.stream().map(MyObject::getId),
    myObject.stream().map(MyObject::getTestId),
    myObject.stream().map(MyObject::getAnotherId)
)
.flatMap(Function.identity())
.collect(Collectors.toList());
  • Related