Is there a way to check condition while streaming a list

时间:2019-04-08 13:57:13

标签: java spring-boot

I have a Persons entity and it has a field contactType. Now according to contact type I want to map List to different resource file ie WorkContactResource or HomeContactResource.I will be using java 8.

workContact=personList.stream().filter(p->p.getPhoneType == PhoneType.WORK).map(WorkResource::new).collect(Collectors.toList());

homeContact=personList.stream().filter(p->p.getPhoneType == PhoneType.HOME).map(HomeResource::new).collect(Collectors.toList());

workContact.addAll(homeContact);

I made to two different List. But what I want is while streaming personsList I would be checking if contactType is home or work and there only map to specific resource. How to achieve this.

2 个答案:

答案 0 :(得分:2)

I believe it should be something like this

abstract class Resource {   
}

class WorkResource extends Resource {
    public WorkResource(Person person) {
        ***********
    }
}

class HomeResource extends Resource {
    public HomeResource(Person person) {
        ***********
    }
}

Map<PhoneType, List<Resource>> contacts = personList.stream().collect(Collectors.groupingBy(p->p.getPhoneType, Collectors.mapping(Resource::new)));

And then iterate through a map by the type

答案 1 :(得分:0)

Given that you want a single list as an output, the most neat would be probably to create a method that does that and refer to it: .map(this::asResource)

public Resource asResource(Person person) {
    if (person.getPhoneType() == PhoneType.WORK) {
        return new WorkResource(person);
    } else {
        return new HomeResource(person);
    }
}

That would make your code look like this:

personList.stream()
        .map(this::asResource)
        .collect(toList());

You can also declare that method in another class, as static so that the usage looks e.g. like this PersonConverter::asResource.