[英]More elegant way to implement
ArrayList<Boolean> values = new ArrayList<>(Arrays.asList(true, false, true, false, false, true));
List<String> filter = Arrays.asList("TRUE");
List<String> filter = Arrays.asList("FALSE");
List<String> filter = Arrays.asList("TRUE","FALSE");
if (!filter.isEmpty()) {
List<Boolean> collect = values.stream()
.filter(i -> i ? filter.contains("TRUE") : filter.contains("FALSE"))
.collect(Collectors.toList());
System.out.println(collect);
} else { System.out.println(values);}
With filter values TRUE
, FALSE
or TRUE,FALSE
I get the desired result [true, true, true]
, [false, false, false]
and [true, false, true, false, false, true]
.使用过滤器值TRUE
, FALSE
或TRUE,FALSE
我得到所需的结果[true, true, true]
, [false, false, false]
和[true, false, true, false, false, true]
。 In case of an empty filter, the list should be returned as is.如果过滤器为空,则应按原样返回列表。 "TRUE" or "FALSE" may represent any String.. “TRUE”或“FALSE”可以代表任何字符串。
Is there a more elegant way to implement?有没有更优雅的实现方式?
If the filter can truly only be the 4 valid combinations, then you can cheat:如果过滤器真的只能是 4 个有效组合,那么你可以作弊:
if (filter.size() == 1) {
Boolean removeTrue = filter.contains("FALSE");
values.removeIf(removeTrue::equals);
}
System.out.println(values);
You can:你可以:
Thus eliminating the if-else
and the extra call to contains()
:因此消除了if-else
和对contains()
的额外调用:
List<Boolean> collect = values.stream()
.filter(i -> filter.isEmpty() || filter.contains(i ? "TRUE" : "FALSE"))
.collect(Collectors.toList());
System.out.println(collect);
I'm not sure what the goal is here but elegance could be in the eye of the beholder so, here you go.我不确定这里的目标是什么,但优雅可能会出现在旁观者的眼中,所以,你去吧。
public static void main(String[] args) {
System.out.println(go(
Arrays.asList(true, false, true, false, false, true),
Arrays.asList("TRUE")));
}
static List<Boolean> go(final List<Boolean> values, final List<String> filter) {
if (filter.isEmpty())
return values;
return values
.stream()
.filter(i -> filter.contains(i.toString().toUpperCase()))
.collect(Collectors.toList());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.