I have created a list of say, 100 configurations. I have partitioned that list into groups of 10, so now I have List<List<Config>>
. All of these configs have a common attribute value, the domainCode
. What's the best way for me to get to that attribute? Say the config domain class looks like this:
public class Config {
private String configId;
private String portfolioId;
private String domainCode;
public Config(String configId, String portfolioId, String domainCode) {
this.configId = configId;
this.portfolioId = portfolioId;
this.domainCode = domainCode;
}
public String getConfigId() { return configId;}
public String getPortfolioSymbolCode() { return portfolioId;}
public String getDomainCode() { return domainCode; }
}
I build 100 of them, then group them:
List<Config> configs = getAllConfigs();
List<List<Config>> partitionedConfigs = new ArrayList<>();
if (configs != null) {
AtomicInteger counter = new AtomicInteger();
partitionedConfigs.addAll(configs.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 10))
.values());
}
I pass partitionedConfigs
to a method. That method needs domainCode
. What's an efficient way to get the single domainCode
out of partitionedConfigs
? Even if there are 100 Config
objects, the domain code is unique, there will only be one domain code. That is the one that my method needs to find.
you can get it from configs
list it self
List<String> domains = configs.stream()
.map(Config::getDomainCode)
.collect(Collectors.toList());
Or from partitionedConfigs
list also
List<String> domains = partitionedConfigs.stream()
.flatMap(List::stream)
.map(Config::getDomainCode)
.collect(Collectors.toList());
If every object in list has same domain name then you can get using findFirst
String domain = configs.stream()
.findFirst()
.map(Config::getDomainCode)
.orElse(null); // if list is empty give some default value
From partitionedConfigs
list
String domain = partitionedConfigs.stream()
.flatMap(List::stream)
.findFirst()
.map(Config::getDomainCode)
.orElse(null); // if list is empty give some