The business scenario

We have a setting table called T_setting, which records the user’s various system Settings

On the front end, however, a form is used instead of an array of set entities (that is, List<SettingEntity>)

To handle this, the background provides a Map object as the return value, which can be understood as SystemSettingVO, where the property is the code of each SettingEntity and the value of the property is value

How to convert List<SettingEntity> to Map?

plan

Let’s start with our SettingEntity

@Data
public class SettingEntity extends IdableEntity {

    private String id;
    
    private String code;
    
    private String value;

}
Copy the code

Let’s convert it to a Map, using Stream, a new Java8 feature

public class SettingService {

    public Map<String, String> getSettingVO(List<SettingEntity> settings) {
        returnsettings.stream().collect(Collectors.toMap(SettingEntity::getCode, SettingEntity::getValue); }}Copy the code

If you need to do something with code and value, such as convert them to int, you can write:

public class SettingService {

    public Map<Integer, Integer> getSettingVO(List<SettingEntity> settings) {
        returnsettings.stream().collect(Collectors.toMap(setting -> Integer.parseInt(setting.getCode()), setting -> Integer.parseInt(setting.getValue()))); }}Copy the code