Posts

Showing posts with the label java8

Careful with Parallel Streams in java 8

List<String> list = new ArrayList<String>() ; //contains about 1000 element List<String> listA = new ArrayList<String>() ; // zezo element now List<String> listB = new ArrayList<String>() ; //zezo element now list.parallelStream().forEach(e -> { if (e.equals( "A" )) { listA .add(e) ; } else { listB .add(e) ; } }) ; list.stream().forEach(e -> { if (e.equals( "A" )) { listA .add(e) ; } else { listB .add(e) ; } }) ; Maybe some guys will think that the above codes with parallelStream () is faster and better than the code with stream () If you try to run it in fact with parallelStream() then it may throw IndexOutOfArrayException, but with stream() is well. Why????? 1. listA.add(e); and listB.add() is not supported using in mutilthread. Your code is not good 2. why it throw IndexOutOfArrayException? please read codes of ArrayList :-) Note:  1. you should use    ...

Understanding Optional.orElse() vs Optional.orElseGet()

In Java, Optional provides a way to handle potentially null values safely. The methods orElse() and orElseGet() are used to provide default values when an Optional is empty. However, the difference between these two methods is important depending on the cost of the default value computation. Step 1: Define the Default Method Let's assume we have a method that returns a default value of type String : public String getDefault () { System. out .println( "Getting Default Value" ); return "Default Value" ; } Step 2: Examine the Two Cases Case 1: Using orElseGet() String name = Optional.of(value) .orElseGet(() -> getDefault()); Here, getDefault() is called only if value is null . This means getDefault() is evaluated lazily (only when needed). Case 2 : Using orElse() String name = Optional.of(value) .orElse(getDefault()); In this case, getDefault() is called always , regardless of whether value is null or not. This means getD...