functional-interface

Java 8 streams, why does this compile part 2… Or what is a method reference, really?

孤街浪徒 提交于 2019-12-03 00:12:35
OK, the first question in this "series" was this one . Now, here is another case: Arrays.asList("hello", "world").stream().forEach(System.out::println); This compiles, and works... OK, in the last question, static methods from a class were used. But now this is different: System.out is a static field of System , yes; it is also a PrintStream , and a PrintStream has a println() method which happens to match the signature of a Consumer in this case, and a Consumer is what forEach() expects . So I tried this... public final class Main { public static void main(final String... args) { Arrays

Thread.sleep inside infinite while loop in lambda doesn't require 'catch (InterruptedException)' - why not?

≯℡__Kan透↙ 提交于 2019-12-02 17:49:43
My question is about InterruptedException , which is thrown from the Thread.sleep method. While working with ExecutorService I noticed some weird behaviour that I don't understand; here is what I mean: ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { while(true) { //DO SOMETHING Thread.sleep(5000); } }); With this code, the compiler doesn't give me any error or message that InterruptedException from Thread.sleep should be caught. But when I am trying to change the loop condition and replace "true" with some variable like this: ExecutorService executor =

Why does a lambda change overloads when it throws a runtime exception?

↘锁芯ラ 提交于 2019-12-02 17:36:55
Bear with me, the introduction is a bit long-winded but this is an interesting puzzle. I have this code: public class Testcase { public static void main(String[] args){ EventQueue queue = new EventQueue(); queue.add(() -> System.out.println("case1")); queue.add(() -> { System.out.println("case2"); throw new IllegalArgumentException("case2-exception");}); queue.runNextTask(); queue.add(() -> System.out.println("case3-never-runs")); } private static class EventQueue { private final Queue<Supplier<CompletionStage<Void>>> queue = new ConcurrentLinkedQueue<>(); public void add(Runnable task) {

Why doesn't Java 8's ToIntFunction<T> extend Function<T, Integer>

时间秒杀一切 提交于 2019-12-01 17:28:59
If I wrote the ToIntFunction interface, i'd want to encode in the interface the fact that it's just a function that returns a primitive int, like this: @FunctionalInterface public interface ToIntFunction<T> extends Function<T, Integer> { int applyAsInt(T value); @Override default Integer apply(T value) { return Integer.valueOf(applyAsInt(value)); } } I was wondering, is there a compelling reason Java 8 API designers chose to keep the primitive alternatives completely separate from Function? Is there some evidence that they considered doing so and decided against it? I guess similar question

How create a new map from the values in an existing map

守給你的承諾、 提交于 2019-12-01 15:29:11
Having the next original map: G1=[7,8,45,6,9] G2=[3,9,34,2,1,65] G3=[6,5,9,1,67,5] Where G1, G2 and G3 are groups of people's ages, How can I create a new map like this: 45=[7,8,45,6,9] 65=[3,9,34,2,1,65] 67=[6,5,9,1,67,5] Where the new keys are the max people's age in each group. I have tried this: Map<Integer, List<Integer>> newMap = originalMap.entrySet().stream() .collect(Collectors.toMap(Collections.max(x -> x.getValue()), x -> x.getValue())); But the compiler say me: "The target type of this expression must be a functional interface" in this fragment of code: Collections.max(x -> x

What is the use of inheriting object class methods in functional interface eg- toString, equals

点点圈 提交于 2019-12-01 12:47:31
I found following code, What is use of inherited equals() and toString() method. @FunctionalInterface public interface FunInterface<T> { // An abstract method declared in the functional interface int test(T o1, T o2); // Re-declaration of the equals() method in the Object class boolean equals(Object obj); String toString(); } The main reason to (re)declare such a method, is to extend and document the contract. In case of Comparator.equals(…) , it’s not that obvious, as it doesn’t specify so much news. It says This method must obey the general contract of Object.equals(Object) . Additionally,

Why to use @FunctionalInterface annotation in Java 8

烂漫一生 提交于 2019-12-01 07:32:39
问题 If we have Interface with only one abstract method in it, it is by default Functional Interface. Can anyone please explain what additional advantage @FunctionalInterface annotation brings? I know that if we add @FunctionalAnnotation, it will not allow someone to add another abstract method in the interface, as it will give a compilation error, but my point is even if you don't use @FucntionalInterface annotation, then also, if someone will add another abstract method, it will break all the

Behavior of Functional Interface and Method Reference

时光怂恿深爱的人放手 提交于 2019-12-01 06:27:48
What happens when the reference of a method which belongs to a variable is destroyed? public class Hey{ public double bar; public Hey(){ bar = 2.0d; } public double square(double num){ return Math.pow(num , bar); } } Function<Double, Double> square; whatsGonnaHappen: { Hey hey = new Hey(); square = hey::square; }//is hey still kept around because its method is being referenced? double ans = square.apply(23d); Scope is a compile time concept that governs where names in source code can be used. From the JLS The scope of a declaration is the region of the program within which the entity declared

Is a class being instantiated in a lambda expression? [duplicate]

你离开我真会死。 提交于 2019-12-01 05:37:09
This question already has an answer here: What is a Java 8 Lambda Expression Compiled to? [duplicate] 1 answer I have the following method invocation, in which I am passing a lambda expression. Is a class being instantiated implicitly here? printStudents( roster, (Student s) -> s.getGender() == Student.Sex.MALE && s.getAge() >= 18 && s.getAge() <= 25 ); Method signature: printStudents(List<Student> roster, CheckStudent checkstudet) interface CheckStudent { boolean test(Student s); } Edit Some of you suggested me to refactor the code, but the same question arises. CheckStudent checkStudent =

Method reference with a full constructor call as a lambda expression in Java

会有一股神秘感。 提交于 2019-12-01 05:18:03
I have encountered a short time ago with a competitive answer better than mine that uses a quite new method reference to me as replacement of lambda. Stream.generate(new AtomicInteger(1)::getAndIncrement)... I looked the Oracle specifications about the Method references and there are defined 4 types: Reference to a static method ContainingClass::staticMethodName Reference to an instance method of a particular object containingObject::instanceMethodName Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName Reference to a constructor ClassName: