0

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 ?

1
  • 3
    List<Long> Ids=myObject.stream().flatMap(o -> Stream.of(o.getJobId(), o.getTestId())) .collect(Collectors.toList()); Commented Oct 8, 2021 at 10:18

3 Answers 3

3

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());

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

2

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.