CaptainBouchon
CaptainBouchon

Reputation: 13

JAVA - How to map efficiently a property from a list to an other?

So i have those two object

public class Setting {

@Id
private Long fooId;

@Transient
private String fooLabel

//GETTER and SETTER ommited
}

and

public class Foo {

@Id
private Long id;

@Column
private String fooLabelEn

@Column
private String fooLabelFr

public getLocalLabel(){}
}

I can easily get the label i need, in english or in an other language, and i want to add it in my list of Setting. I can't modify the Foo table, and i can't save all label in Setting.

I tried something like this, but it's not really efficent.

fooList = fooRepository.findAllById(settingIdList);
settingList.stream()
    .map(setting -> setting.setLabel(fooList.stream()
        .filter(foo -> foo.getId().equals(setting.getFooId())
        .findFirst()
        .get()
        .getLocalLabel)
    )
    .collect(Collectors.toList());

I think i forgot something, and i feel i don't go in the right direction. I can only save ids for the settings, so i have to do something like this.

Does anyone have a complient solution ?

Thanks for the help.

Upvotes: 1

Views: 64

Answers (1)

Eteka Christopher
Eteka Christopher

Reputation: 133

Just to help explain better what @tevemadar suggested, since you have been able to retrieve fooList from the data source, you can go extra mile by turning the result to a map, as follows:

Map<Long, Foo> fooMap = fooRepository.findAllById(settingIdList).stream().collect(Collectors.toMap(Foo::getId, foo -> foo))

So you can now do the following:

settingList.stream()
    .peek(setting -> setting.setLabel(fooMap.get(setting.getFooId()).getLocalLabel()))
    .collect(Collectors.toList());

One can argue this may not be entirely null safe, suppose you cannot find setting.getFooId() in fooMap. Something you can do is:

settingList.stream()
    .peek(setting -> setting.setLabel(fooMap.getOrDefault(setting.getFooId(), new Foo(-1)).getLocalLabel()))
    .collect(Collectors.toList());

where new Foo(-1) creates a naive instance of foo with it's localLabel set to -1. It totally now depends on your implementation, you may not want this.

Upvotes: 1

Related Questions