Java 8 stream filtering: IN clause

旧巷老猫 提交于 2021-01-27 07:07:29

问题


List<Y> tmp= new DATA<Y>().findEntities();
List<X> tmp1 = new DATA<X>().findEntities().stream().filter(
                        IN (tmp) ???
                ).collect(Collectors.toList());

How to simulate a tipical IN clause (like in mysql or JPA) using a Predicate ?


回答1:


I decided to update my comment to an answer. The lambda expression for your requested Predicate<Y> (where Y should be a concrete type) looks as following:

element -> tmp.contains(element)

Because the collection's contains method has the same signature as the predicate's test method, you can use a method reference (here an instance method reference):

tmp::contains

A full example:

List<Number> tmp = Arrays.asList(1, 2, 3);
List<Integer> tmp1 = Arrays
    .stream(new Integer[] { 1, 2, 3, 4, 5 })
    .filter(tmp::contains)
    .collect(Collectors.toList());
System.out.println(tmp1);

This prints

[1, 2, 3]


来源:https://stackoverflow.com/questions/26161830/java-8-stream-filtering-in-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!