Posts

Showing posts with the label java-8

How best to determine if a String contains only null characters?

5 1 What's the right way to check if a string contains null characters only? String s = "\u0000"; if(s.charAt(0) == 0) { System.out.println("null characters only"); } Or String s = "\0\0"; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == 0) continue; else break; } Both work. But is there a better and more concise way to perform this check. Is there a utility to check if a string in java contains only null characters( \u0000 OR \0 ) ? And what is the difference between '\0' and '\u0000' ? java string java-8 char null-character ...

Check if all values of a map are true

0 2 I have one Map<String, Boolean> map = new HashMap<>(); . Consider there are five keys in it. map.put("A", true); map.put("B", true); map.put("C", false); map.put("D", true); map.put("E", true); I need to set one boolean flag as true if all the values in the above map are true. If any value is false then i need to set boolean flag as false I can iterate this map and do it like old ways but i want to know how can i do this in a single line by streaming on this map. java java-8 hashmap java-stream Share ...

Why does the Java compiler 11 use invokevirtual to call private methods?

45 3 When compiling the code below with the Java compiler from OpenJDK 8, the call to foo() is done via an invokespecial , but when OpenJDK 11 is used, an invokevirtual is emitted. public class Invoke { public void call() { foo(); } private void foo() {} } Output of javap -v -p when javac 1.8.0_282 is used: public void call(); descriptor: ()V flags: (0x0001) ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #2 // Method foo:()V 4: return Output of javap -v -p when javac 11.0.10 is used: public void call(); descriptor: ()V flags: (0x0001) ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokevirtual #2 // Method foo:...

Java method can't be applied with Lambda expression

I've watched and read https://caveofprogramming.com/java/whats-new-in-java-8-lambda-expressions.html and I follow the same pattern I did for runner object which works fine. Runner runner = new Runner(); runner.run(() -> System.out.println("Print from Lambda expression")); Then, I try to create a simple interface and class to apply what I learned. I just want to replace the anonymous class with a lambda expression. My understanding is a lambda expression is a shorter code for the anonymous class and improve readability. So, I tried to initiate another instance called eucalyptus1 and try to @Override the grow() method, but my IDE error message said: grow() in com.smith.Eucalyptus cannot be applied to (lambda expression) Could anyone point me out what I misunderstand here? The code is below: // a simple interface interface Plant { public void grow(); } // apply interface to class class Eucalyptus implements Plant { @Override public void grow() { Syst...

Java 8 Stream API - Does any stateful intermediate operation guarantee a new source collection?

Is the following statement true? (Source and source - they seem to copy from each other or come from the same source.) The sorted() operation is a “stateful intermediate operation”, which means that subsequent operations no longer operate on the backing collection, but on an internal state. I have tested Stream::sorted as a snippet from sources above: final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList()); list.stream() .filter(i -> i > 5) .sorted() .forEach(list::remove); System.out.println(list); // Prints [0, 1, 2, 3, 4, 5] It works. I replaced Stream::sorted with Stream::distinct, Stream::limit and Stream::skip: final List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList()); list.stream() .filter(i -> i > 5) .distinct() .forEach(list::remove); // Throws NullPointerException To my surprise, the NullPointerException is thrown. All the tested methods follow the...

Java 8+ stream: Check if list is in the correct order for two fields of my object-instances

The title may be a bit vague, but here is what I have (in privatized code): A class with some fields, including a BigDecimal and Date: class MyObj{ private java.math.BigDecimal percentage; private java.util.Date date; // Some more irrelevant fields // Getters and Setters } In another class I have a list of these objects (i.e. java.util.List<MyObj> myList). What I want now is a Java 8 stream to check if the list is in the correct order of both dates and percentages for my validator. For example, the following list would be truthy: [ MyObj { percentage = 25, date = 01-01-2018 }, MyObj { percentage = 50, date = 01-02-2018 }, MyObj { percentage = 100, date = 15-04-2019 } ] But this list would be falsey because the percentage aren't in the correct order: [ MyObj { percentage = 25, date = 01-01-2018 }, MyObj { percentage = 20, date = 01-02-2018 }, MyObj { percentage = 100, date = 15-04-2019 } ] And this list would also be falsey because the dates aren't in the c...

How to iterate over lambda functions in Java

I was able to do it in Python and my Python code is: signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} a = 5 b = 3 for i in signs.keys(): print(signs[i](a,b)) And the output is: 8 2 How do I do this same thing in Java through HashMap? You can use BinaryOperator<Integer> in this case like so : BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b // Then create a new Map which take the sign and the corresponding BinaryOperator // equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub); int a = 5; // a = 5 int b = 3; // b = 3 // Loop over the sings map and apply the operation signs.values().forEach(v -> System.out.println(v.apply(a, b))); Outputs 8 2 Note for Map.of("+", add, "-...

Optional isPresent vs orElse(null)

I was updating the dependencies to Spring 5 in my project and was bombarded with compilation errors where the method definition of findOne() has been replaced by findById() which now returns an Optional (correct me if I am wrong). While refactoring, I came across multiple approaches that I can choose to adopt, and I would therefore like some input on which one is to be preferred. 1st approach: ExpectedPackage ep = expectedPackageRepository.findById(1).orElse(null); if(ep != null){ ep.setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep); } 2nd approach: Optional<ExpectedPackage> ep = expectedPackageRepository.findById(1); if(ep.isPresent()){ ep.get().setDateModified(new Date()); expectedPackageRepository.saveAndFlush(ep.get()); } Or is there a third and better approach that I have missed? I went through several questions and a couple of articles, but I did not find a clear answer. You can also do: expectedPackageRepository.findById(1).ifPres...

Example of non-interference in Java 8

According to this question, we can modify the source and it's not called interference: you can modify the stream elements themselves and it should not be called as "interference". According to this question, the code List<String> list = new ArrayList<>(); list.add("test"); list.forEach(x -> list.add(x)); will throw ConcurrentModificationException. But my code, Employee[] arrayOfEmps = { new Employee(1, "Jeff Bezos"), new Employee(2, "Bill Gates"), new Employee(3, "hendry cavilg"), new Employee(4, "mark cuban"), new Employee(5, "zoe"), new Employee(6, "billl clinton"), new Employee(7, "ariana") , new Employee(8, "cathre"), new Employee(9, "hostile"), new Employee(10, "verner"), ...

Java8 Stream : Collect elements after a condition is met

My POJO is as follows class EventUser { private id; private userId; private eventId; } I retrieve EventUser object as follows: List<EventUser> eventUsers = eventUserRepository.findByUserId(userId); Say the 'eventUsers' is as follows: [ {"id":"id200","userId":"001","eventId":"1010"}, {"id":"id101","userId":"001","eventId":"4212"}, {"id":"id402","userId":"001","eventId":"1221"}, {"id":"id301","userId":"001","eventId":"2423"}, {"id":"id701","userId":"001","eventId":"5423"}, {"id":"id601","userId":"001","eventId":"7423"} ] Using streaming, and without using any intermediate variable , how can I filter and collect eve...

Meaning of lambda () -> { } in Java

I am looking at the following Stack Overflow answer: How to change Spring's @Scheduled fixedDelay at runtime And in the code there is the following line: schedulerFuture = taskScheduler.schedule(() -> { }, this); I would like to know what the lambda () -> {} means in that code. I need to write it without using lambdas. Its a Runnable with an empty run definition. The anonymous class representation of this would be: new Runnable() { @Override public void run() { // could have done something here } } Lamda expression is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code. They have no access modifier(private, public or protected), no return type declaration and no name. Lets take a look at this example. (int a, int b) -> {return a > b} In your case, you can do something like below: schedulerFuture = taskScheduler.schedule(new Runnable() { @Override ...