Java 使一种方法在不同条件下使用lambda打印
所以我有这个代码:Java 使一种方法在不同条件下使用lambda打印,java,lambda,Java,Lambda,所以我有这个代码: ArrayList<Meeting>[] calendary = new ArrayList[31]; 任务是使一个方法接受lambda来打印数组“calendary”中的元素,但我不知道如何实现这一点。 它可以从status==true的日历中打印会议,或者打印所有元素 其中description==“某物”。我们在方法parametr中传递条件,如下所示: ArrayList<Meeting>[] calendarys = new ArrayLi
ArrayList<Meeting>[] calendary = new ArrayList[31];
任务是使一个方法接受lambda来打印数组“calendary”中的元素,但我不知道如何实现这一点。
它可以从status==true的日历中打印会议,或者打印所有元素
其中description==“某物”。我们在方法parametr中传递条件,如下所示:
ArrayList<Meeting>[] calendarys = new ArrayList[31];
List<Meeting> meet = new ArrayList<>();
List<Meeting> sth = new ArrayList<>();
Arrays.stream(calendarys).map(calendary -> {
if (calendary.getStatus()) {
meet.add(calendary); //collect meetings
} else if (calendary.getDescription().equals("sth") {
sth.add(calendary); //collect all describtion == "sth"
}
return null;
});
ArrayList[]calendarys=新的ArrayList[31];
List meet=new ArrayList();
列出某物=新的数组列表();
Arrays.stream(calendarys).map(calendary->{
if(calendary.getStatus()){
meet.add(日历);//收集会议
}如果(calendary.getDescription()等于(“某事物”){
添加(日历);//收集所有描述==“某物”
}
返回null;
});
首先,你确定这个结构吗?列表数组并不好
通过将多个谓词
传递到一个可以为您过滤值的方法中,您可以轻松实现这一点
private static List<Meeting>[] filtered(List<Meeting>[] list, Predicate<Meeting>... predicates) {
// No predicates, no filter
if (predicates == null || predicates.length == 0) {
return list;
}
// Build one Predicate from others
Predicate<Meeting> predicate = Arrays.stream(predicates)
.reduce(Predicate::and)
.orElse(p -> true);
// Filter the meetings and return in the original data structure
return Arrays.stream(list)
.map(meetingList -> meetingList == null ? null :
meetingList.stream()
.filter(predicate)
.collect(Collectors.toList()))
.toArray(List[]::new);
}
私有静态列表[]已筛选(列表[]列表,谓词…谓词){
//没有谓词,就没有筛选器
如果(谓词==null | |谓词.length==0){
退货清单;
}
//从其他谓词构建一个谓词
谓词=数组.流(谓词)
.reduce(谓词::and)
.orElse(p->true);
//过滤会议并返回原始数据结构
返回Arrays.stream(列表)
.map(meetingList->meetingList==null?null:
meetingList.stream()
.filter(谓词)
.collect(收集器.toList())
.toArray(列表[]::新建);
}
请记住,如果在出现
List
类型实例的位置出现null
时,代码将失败。因此,请使用三元运算符立即返回null
列表,而不是试图在其上进行流式处理,这会击中NPE…或者更好,请确保传递正确的对象或使用d不同且更灵活的数据结构。“生成一个lambda方法”,从问题的其余部分判断,您确定您的意思不是“生成一个方法接受一个lambda/谓词”?听起来您想要一个打印所有匹配元素的方法,以及“匹配”是您可以传入的内容。您的代码是java代码而不是c#,因此请更改标记或更改代码您可以动态指定谓词。请参阅比较字符串与==
,呃!equals
,或equalsIgnoreCase
中的“使用切换语句进行筛选”部分。是的,