private void func(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { // ...pred.test is OK } else if (o instanceof Collection && ((Collection) o).stream().filter(i -> i instanceof Map).anyMatch(pred)) { // ...anyMatch here gives the above error }}
private void func(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { // ...pred.test is OK } else if (o instanceof Collection && ((Collection) o).stream().filter(i -> i instanceof Map).<Map>map(Map.class::cast).anyMatch(pred)) { // ...anyMatch now works }}
或者使用更简洁的类型转换:
private void func(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { // ...pred.test is OK } else if (o instanceof Collection && ((Collection) o).stream().filter(i -> i instanceof Map).map(i -> (Map) i).anyMatch(pred)) { // ...anyMatch now works }}
private void func(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { // ...pred.test is OK } else if (o instanceof Collection && ((Collection) o).stream() .<Map>mapMulti((i, consumer) -> { if (i instanceof Map m) consumer.accept(m); }) .anyMatch(pred)) { // ...anyMatch now works }}
import java.util.Collection;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.function.Predicate;public class StreamPredicateExample { private void funcWithMap(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { System.out.println("Direct Map test OK"); } else if (o instanceof Collection) { boolean anyMatch = ((Collection) o).stream() .filter(i -> i instanceof Map) .map(i -> (Map) i) // Using map for type conversion .anyMatch(pred); System.out.println("Collection with map using map: " + anyMatch); } } private void funcWithMapMulti(Object o) { Predicate<Map> pred = m -> true; if (o instanceof Map && pred.test((Map) o)) { System.out.println("Direct Map test OK"); } else if (o instanceof Collection) { boolean anyMatch = ((Collection) o).stream() .<Map>mapMulti((i, consumer) -> { // Using mapMulti for type conversion and filtering if (i instanceof Map m) consumer.accept(m); }) .anyMatch(pred); System.out.println("Collection with map using mapMulti: " + anyMatch); } } public static void main(String[] args) { StreamPredicateExample example = new StreamPredicateExample(); Map map = new HashMap(); map.put("key1", 1); map.put("key2", 2); List list = List.of("string", 123, map, new HashMap()); example.funcWithMap(map); example.funcWithMap(list); example.funcWithMapMulti(map); example.funcWithMapMulti(list); }}
给滚动元素平滑过渡 如何在滚动条属性(scrollleft)发生改变时为元素添加平滑的过渡效果? 解决方案:scroll-behavior 属性 为滚动容器设置 scroll-behavior 属性可以实现平滑滚动。 html 代码: click the button to slide right!…
如何在前端实现 Windows 10 设置界面中的鼠标移动探照灯效果 想要在前端开发中实现 Windows 10 设置界面中类似的鼠标移动探照灯效果,可以通过以下途径: CSS 解决方案 DEMO 1: Windows 10 网格悬停效果:https://codepen.io/tr4553r7/pe…