Reputation: 110
I have the following classes:
@Getter
public class SomeClass implements Serializable {
private LocalDate date;
private String smth;
List<PairKeyValue> quotaParams;
}
The class PairKeyValue is just:
@Getter
public class PairKeyValue implements Serializable {
private String key;
private String value;
}
I want to do the following:
1) Check if in SomeClass's
date equals sysdate then check value under key="somekey"
in list<PairKeyValue>
is equals to 1 (somekey = 1
) then left it in list.
2) Check if in SomeClass's
date
NOT equals sysdate
then check value under key="somekey"
in List<PairKeyValue>
is equals to 0 (somekey = 0
) then left it in list.
3) And ignore other values.
So in the end I need a filtered list of only current values within SomeClass
.
I have my realization but I don't like it is not using only stream API:
availableQuotes = ArrayList();
if (CollectionUtils.isNotEmpty(availableQuotes)) {
availableQuotes = availableQuotes
.stream()
.filter(this::checkDate).collect(toList());
}
private boolean checkDate (SomeClass someClass){
if (someClass.getDate().equals(LocalDate.now())) {
return checkDuration(someClass, "0");
} else {
return checkDuration(someClass, "1");
}
}
private boolean checkDuration (SomeClass someClass, String param){
List<PairKeyValue> quotaParams = someClass.getPairKeyValues().stream()
.filter(spKeyValue -> spKeyValue.getKey().equals("duration"))
.filter(spKeyValue -> spKeyValue.getValue().equals(param))
.collect(toList());
return (CollectionUtils.isNotEmpty(quotaParams));
}
I know it looks awful and I know it can be more readable so please help.
Upvotes: 0
Views: 92
Reputation: 2096
If I understood your question right, the last 2 functions can be resumed to the following:
availableQuotes = availableQuotes.stream()
.filter(availableQuote -> availableQuote.getQuotaParams().stream()
.anyMatch(quotaParam -> quotaParam.getKey().equals("duration")
&& quotaParam.getValue().equals(availableQuote.getDate().equals(LocalDate.now()) ? "0" : "1")))
.collect(Collectors.toList());
I mostly took your code and re-arranged it into a single filter.
Upvotes: 1