archive-cr.com » CR » I » INFORMATECH.CR

Total: 292

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Java 8 Streams and JPA | Informatech CR Blog
    and transform it into a Spliterator by doing private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it StreamSupport stream spliterator false At this point we have built enough to create our first stream out of a JPQL query We can do it as follows public Stream T getResultStream String sql Integer fetchSize Map String Object parameters Query query session createQuery sql if fetchSize null query setFetchSize fetchSize for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue query setReadOnly true ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close A JPA Stream API We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API public interface StreamQuery T Stream T getResultStream StreamQuery T setParameter String name Object value StreamQuery T setFetchSize int fetchSize And putting together all we have learned so far we could create this implementation of our new StreamQuery interface public class HibernateQueryStream T implements StreamQuery T private final Session session private final String sql private final Class T type private final Map String Object parameters new HashMap private Integer fetchSize public HibernateQueryStream EntityManager entityManager String sql Class T type this session entityManager unwrap Session class this sql sql this type type Override public StreamQuery T setParameter String name Object value parameters put name value return this Override public StreamQuery T setFetchSize int fetchSize this fetchSize fetchSize return this Override public Stream T getResultStream Query query session createQuery sql if fetchSize null query setFetchSize fetchSize query setReadOnly true for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE private static class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 The Repository Layer On top of this component we can now build our repository layer Repository public class StreamRepository PersistenceContext unitName demo private EntityManager entityManager public Stream Order getOrderHistory String email String jpql SELECT o FROM Order o WHERE o customer email email StreamQuery Order query new HibernateQueryStream entityManager jpql Order class return query getResultStream And from here the rest is a piece of cake orderRepository findOrderHistory email filter order order total 100 map Order getOrderLines flatMap List stream map OrderLine getTotal reduce 0 x y x y It is important to highlight that the Hibernate session must

    Original URL path: http://blog.informatech.cr/2014/12/17/java8-jpa-streams/ (2015-08-19)
    Open archived version from archive


  • Edwin Dalorzo | Informatech CR Blog
    just a Function T T Thus some our declarations above could be slightly simplified with this functional interface UnaryOperator Integer add1 n n 1 UnaryOperator String concat1 s s 1 Function Integer UnaryOperator Integer sum x y x y UnaryOperator Integer sum10 sum apply 10 I have already written another article that explains Why Java 8 has Interface Pollution like this in case you are interested in an explanation Value Types and Primitive Type Functions Evidently using a type like Integer incurs into the costs of boxing and unboxing when our functions have to deal with a primitive type like int As you know Java does not support value types as type arguments in generic declarations so to deal with this problem we can use alternative functional interfaces like ToIntFunction IntFunction or IntUnaryOperator Or we can define our own primitive function interface IntFx public int apply int value Then we can do IntFx add1 n n 1 IntFunction IntFx sum x y x y IntFx sum10 sum apply 10 sum10 apply 4 yields 14 Similar functional interfaces can be found in the Java API for types double and long as well This topic is also covered in the alternative article mentioned above about interface pollution And that s it for the time being I hope that in a future article I can take this a bit further and show some practical applications derived from my experience in actual projects Further Reading High Order Programming High Order Functions Function Composition Currying Why Java 8 has Interface Pollution Share this Email Facebook Twitter Like this Like Loading October 19 2014 by Edwin Dalorzo Categories Java Programming Tags function composition functional programming high java java8 Leave a comment Why There Is Interface Pollution in Java 8 I was reading this interesting post about The Dark Side of Java 8 In it Lukas Eder the author mentions how bad it is that in the JDK 8 the types are not simply called functions For instance in a language like C there is a set of predefined function types accepting any number of arguments with an optional return type Func and Action each one going up to 16 parameters of different types T1 T2 T3 T16 but in the JDK 8 what we have is a set of different functional interfaces with different names and different method names and whose abstract methods represent a subset of well know function signatures function arities i e nullary unary binary ternary etc The Type Erasure Issue So in a way both languages suffer from some form of interface pollution or delegate pollution in C The only difference is that in C they all have the same name In Java unfortunately due to type erasure there is no difference between Function T1 T2 and Function T1 T2 T3 or Function T1 T2 T3 Tn so evidently we couldn t simply name them all the same way and we had to come up with creative names for all possible types of function combinations Don t think the expert group did not struggle with this problem In the words of Brian Goetz in the lambda mailing list As a single example let s take function types The lambda strawman offered at devoxx had function types I insisted we remove them and this made me unpopular But my objection to function types was not that I don t like function types I love function types but that function types fought badly with an existing aspect of the Java type system erasure Erased function types are the worst of both worlds So we removed this from the design But I am unwilling to say Java never will have function types though I recognize that Java may never have function types I believe that in order to get to function types we have to first deal with erasure That may or may not be possible But in a world of reified structural types function types start to make a lot more sense So how does this affect us as developers The following is a categorization of some of the most important new functional interfaces and some old ones in the JDK 8 organized by function return type and the number of expected arguments in the interface method Functions with Void Return Type In the realm of functions with a void return type we have the following Type of Function Lambda Expression Known Functional Interfaces Nullary doSomething Runnable Unary foo System out println foo Consumer IntConsumer LongConsumer DoubleConsumer Binary console text console print text BiConsumer ObjIntConsumer ObjLongConsumer ObjDoubleConsumer n ary sender host text sender send host text Define your own Functions with Some Return Type T In the realm of functions with a return type T we have the following Type of Function Lambda Expression Known Functional Interfaces Nullary Hello World Callable Supplier BooleanSupplier IntSupplier LongSupplier DoubleSupplier Unary n n 1 n n 0 Function IntFunction LongFunction DoubleFunction IntToLongFunction IntToDoubleFunction LongToIntFunction LongToDoubleFunction DoubleToIntFunction DoubleToLongFunction UnaryOperator IntUnaryOperator LongUnaryOperator DoubleUnaryOperator Predicate IntPredicate LongPredicate DoublePredicate Binary a b a b 1 0 x y x y x y x y 0 Comparator BiFunction ToIntBiFunction ToLongBiFunction ToDoubleBiFunction BinaryOperator IntBinaryOperator LongBinaryOperator DoubleBinaryOperator BiPredicate n ary x y z 2 x Math sqrt y z Define your own An advantage of this approach is that we can define our own interface types with methods accepting as many arguments as we would like and we could use them to create lambda expressions and method references as we see fit In other words we have the power to pollute the world with yet even more new functional interfaces Also we can create lambda expressions even for interfaces in earlier versions of the JDK or for earlier versions of our own APIs that defined SAM types like these And so now we have the power to use Runnable and Callable as functional interfaces However these interfaces become more difficult to memorize since they all have different names and methods Still I am one of those wondering why they didn t solve the problem as in Scala defining interfaces like Function0 Function1 Function2 FunctionN Perhaps the only argument I can come up with against that is that they wanted to maximize the possibilities of defining lambda expressions for interfaces in earlier versions of the APIs as mentioned before Lack of Value Types So evidently type erasure is one driving force here But if you are one of those wondering why we also need all these additional functional interfaces with similar names and method signatures and whose only difference is the use of a primitive type then let me remind you that in Java we also lack of value types like those in a language like C This means that the generic types used in our generic classes can only be reference types and not primitive types In other words we can t do this List int numbers asList 1 2 3 4 5 But we can indeed do this List Integer numbers asList 1 2 3 4 5 The second example though incurs in the cost of boxing and unboxing of the wrapped objects back and forth from to primitive types This can become really expensive in operations dealing with collections of primitive values So the expert group decided to create this explosion of interfaces to deal with the different scenarios To make things less worse they decided to only deal with three basic types int long and double Quoting the words of Brian Goetz in the lambda mailing list More generally the philosophy behind having specialized primitive streams e g IntStream is fraught with nasty tradeoffs On the one hand it s lots of ugly code duplication interface pollution etc On the other hand any kind of arithmetic on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive specialization The available language based solutions were losers from a complexity value tradeoff Though there are some alternative solutions we are going to continue to explore though clearly not for 8 and probably not for 9 either In the meantime you have the tools to do what you want I get that you prefer we provide that last mile for you and secondarily your request is really a thinly veiled request for why don t you just give up on checked exceptions already but I think the current state lets you get your job done So it s up to us the developers to craft yet even more interface explosions to deal with these in a case by case basis interface IOConsumer T void accept T t throws IOException static T Consumer T exceptionWrappingBlock IOConsumer T b return e try b accept e catch Exception ex throw new RuntimeException ex In order to do Writer out new StringWriter Consumer String printer exceptionWrappingBlock s out write s Probably in the future maybe JDK 9 when we get Support for Value Types in Java and Reification we will be able to get rid of or at least no longer need to use anymore these multiple interfaces In summary we can see that the expert group struggled with several design issues The need requirement or constraint to keep backwards compatibility made things difficult then we have other important conditions like the lack of value types type erasure and checked exceptions If Java had the first and lacked of the other two the design of JDK 8 would probably have been different So we all must understand that these were difficult problems with lots of tradeoffs and the EG had to draw a line somewhere and make a decisions So when we find ourselves in the dark side of Java 8 probably we need to remind ourselves that there is a reason why things are dark in that side of the JDK Further Reading Related Answer in Stackoverflow Lambda Straw Man Proposal Neal Gafter on The Future of Java Share this Email Facebook Twitter Like this Like Loading April 4 2014 by Edwin Dalorzo Categories Java Programming 14 Comments Memoized Fibonacci Numbers with Java 8 Since today is Fibonacci Day I decided that it would be interesting to publish something related to it I believe one of the first algorithms we all see when learning non linear recursion is that of calculating a Fibonacci number I found a great explanation on the subject in the book Structure and Interpretation of Computer Programs SIC and I dedicated some time to playing with the Fibonacci algorithm just for fun While doing so I found an interesting way to improve the classical recursive algorithm by using one of the new methods added in Java 8 in the Map interface and which I used here to implement a form of memoization Classical Recursive Fibonacci In the classical definition of Fibonacci we learn that We program this very easily in Java public static long fibonacci int x if x 0 x 1 return x return fibonacci x 1 fibonacci x 2 Now the problem with this algorithm is that with the exception of the base case we recursively invoke our function twice and interestingly one of the branches recalculates part of other branch every time we invoke the function Consider the following image taken from SIC that represents an invocation to fibonacci 5 Clearly the branch to the right is redoing all the work already done during the recursive process carried out by the left branch Can you see how many times fibonacci 2 was calculated The problem gets worse as the function argument gets bigger In fact this problem is so serious that the calculation of a small argument like fibonacci 50 might take quite a long time Memoized Recursive Fibonacci However there is a way to improve the performance of the original recursive algorithm I mean without having to resort to a constant time algorithm using for instance Binet s formula The serious problem we have in the original algorithm is that we do too much rework So we could alleviate the problem by using memoization in other words by providing a mechanism to avoid repeated calculations by caching results in a lookup table that can later be used to retrieve the values of already processed arguments In Java we could try to store the Fibonacci numbers in a hast table or map In the case of the left branch we ll have to run the entire recursive process to obtain the corresponding Fibonacci sequence values but as we find them we update the hash table with the results obtained This way the right branches will only perform a table lookup and the corresponding value will be retrieved from the hash table and not through a recursive calculation again Some of the new methods in the class Map in Java 8 simplify a lot the writing of such algorithm particularly the method computeIfAbsent key function Where the key would be the number for which we would like to look up the corresponding Fibonacci number and the function would be a lambda expression capable of triggering the recursive calculation if the corresponding value is not already present in the map So we can start by defining a map and putting the values in it for the base cases namely fibonnaci 0 and fibonacci 1 private static Map Integer Long memo new HashMap static memo put 0 0L fibonacci 0 memo put 1 1L fibonacci 1 And for the inductive step all we have to do is redefine our Fibonacci function as follows public static long fibonacci int x return memo computeIfAbsent x n fibonacci n 1 fibonacci n 2 As you can see the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map this recursive process will be triggered entirely for the left branch but the right branch will use the momoized values This represents a significant improvement Based on my subjective observation this improved recursive version was outstandingly faster for a discrete number like fibonacci 70 With this algorithm we can safely calculate up to fibonacci 92 without running into long overflow Even better to be sure that our algorithm would never cause overflows without letting the user know we could also use one of the new methods in Java 8 added to the Math class and which throws an ArithmeticException when overflow occurs So we could change our code as follows public static long fibonacci int x return memo computeIfAbsent x n Math addExact fibonacci n 1 fibonacci n 2 This method would start failing for fibonacci 93 If we need to go over 92 we would have to use BigInteger in our algorithm instead of just long Notice that the memozied example uses mutations therefore in order to use this code in a multithreaded environment we would first need to add some form of synchronization to the proposed code or use a different map implementation perhaps a ConcurrentHashMap which evidently may impact performance as well Arguably this would still be better than the original recursive algorithm Share this Email Facebook Twitter Like this Like Loading May 8 2013 by Edwin Dalorzo Categories Java Tags fibonacci java 7 Comments Java 8 Optional Objects In this post I present several examples of the new Optional objects in Java 8 and I make comparisons with similar approaches in other programming languages particularly the functional programming language SML and the JVM based programming language Ceylon this latter currently under development by Red Hat I think it is important to highlight that the introduction of optional objects has been a matter of debate In this article I try to present my perspective of the problem and I do an effort to show arguments in favor and against the use of optional objects It is my contention that in certain scenarios the use of optional objects is valuable but ultimately everyone is entitled to an opinion and I just hope this article helps the readers to make an informed one just as writing it helped me understand this problem much better About the Type of Null In Java we use a reference type to gain access to an object and when we don t have a specific object to make our reference point to then we set such reference to null to imply the absence of a value In Java null is actually a type a special one it has no name we cannot declare variables of its type or cast any variables to it in fact there is a single value that can be associated with it i e the literal null and unlike any other types in Java a null reference can be safely assigned to any other reference types See JLS 3 10 7 and 4 1 The use of null is so common that we rarely meditate on it field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don t have an initial value to give them and in general null is used everywhere to imply that at certain point we don t know or we don t have a value to give to a reference About the Null Pointer Reference Problem Now the major problem with the null reference is that if we try to dereference it then we get the ominous and well known NullPointerException When we work with a reference obtained from a different context than our code i e as the result of a method invocation or when we receive a reference as an argument in a method we are working on we all would like to avoid this error that has the potential to make our application crash but often the problem is not noticed early enough and it finds its way into production code where it waits for the right moment to fail which is typically a Friday at the end of the month around 5 p m and just when you are about to leave the office to go to the movies with your family or drink some beers with your friends To make things worse the place where your code fails is rarely the place where the problem originated since your reference could have been set to null far away from the place in your code where you intended to dereference it So you better cancel those plans for the Friday night It s worth mentioning that this concept of null references was first introduced by Tony Hoare the creator of ALGOL back in 1965 The consequences were not so evident in those days but he later regretted his design and he called it a billion dollars mistake precisely referring to the uncountable amount of hours that many of us have spent since then fixing this kind null dereferencing problems Wouldn t it be great if the type system could tell the difference between a reference that in a specific context could be potentially null from one that couldn t This would help a lot in terms of type safety because the compiler could then enforce that the programmer do some verification for references that could be null at the same time that it allows a direct use of the others We see here an opportunity for improvement in the type system This could be particularly useful when writing the public interface of APIs because it would increase the expressive power of the language giving us a tool besides documentation to tell our users that a given method may or may not return a value Now before we delve any further I must clarify that this is an ideal that modern languages will probably pursue we ll talk about Ceylon and Kotlin later but it is not an easy task to try to fix this hole in a programming language like Java when we intend to do it as an afterthought So in the coming paragraphs I present some scenarios in which I believe the use of optional objects could arguably alleviate some of this burden Even so the evil is done and nothing will get rid of null references any time soon so we better learn to deal with them Understanding the problem is one step and it is my opinion that these new optional objects are just another way to deal with it particularly in certain specific scenarios in which we would like to express the absence of a value Finding Elements There is a set of idioms in which the use of null references is potentially problematic One of those common cases is when we look for something that we cannot ultimately find Consider now the following simple piece of code used to find the first fruit in a list of fruits that has a certain name public static Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return fruit return null As we can see the creator of this code is using a null reference to indicate the absence of a value that satisfies the search criteria 7 It is unfortunate though that it is not evident in the method signature that this method may not return a value but a null reference Now consider the following code snippet written by a programmer expecting to use the result of the method shown above List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Fruit found find lemon fruits some code in between and much later on or possibly somewhere else String name found getName uh oh Such simple piece of code has an error that cannot be detected by the compiler not even by simple observation by the programmer who may not have access to the source code of the find method The programmer in this case has naively failed to recognize the scenario in which the find method above could return a null reference to indicate the absence of a value that satisfies his predicate This code is waiting to be executed to simply fail and no amount of documentation is going to prevent this mistake from happening and the compiler will not even notice that there is a potential problem here Also notice that the line where the reference is set to null 5 is different from the problematic line 7 In this case they were close enough in other cases this may not be so evident In order to avoid the problem what we typically do is that we check if a given reference is null before we try to dereference it In fact this verification is quite common and in certain cases this check could be repeated so many times on a given reference that Martin Fowler renown for hist book on refactoring principles suggested that for these particular scenarios such verification could be avoided with the use of what he called a Null Object In our example above instead of returning null we could have returned a NullFruit object reference which is an object of type Fruit that is hollowed inside and which unlike a null reference is capable of properly responding to the same public interface of a Fruit Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value for instance to a maximum or minimum value Consider the following piece of code that can be used to determine which is the longest string in a collection public static String longest Collection String items if items isEmpty return null Iterator String iter items iterator String result iter next while iter hasNext String item iter next if item length result length result item return result In this case the question is what should be returned when the list provided is empty In this particular case a null value is returned once again opening the door for a potential null dereferencing problem The Functional World Strategy It s interesting that in the functional programming paradigm the statically typed programming languages evolved in a different direction In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value The following piece of code shows the definition of the SML option type datatype a option NONE SOME of a As you can see option is a data type with two constructors one of them stores nothing i e NONE whereas the other is capable of storing a polymorphic value of some value type a where a is just a placeholder for the actual type Under this model the piece of code we wrote before in Java to find a fruit by its name could be rewritten in SML as follows fun find name fruits case fruits of NONE Fruit s fs if s name then SOME Fruit s else find name fs There are several ways to achieve this in SML this example just shows one way to do it The important point here is that there is no such thing as null instead a value NONE is returned when nothing is found 3 and a value SOME fruit is returned otherwise 5 When a programmer uses this find method he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE 6 or SOME fruit 7 somewhat like this let val fruits Fruit apple Fruit grape Fruit orange val found find grape fruits in case found of NONE print Nothing found SOME Fruit f print Found fruit f end Having to check for the true nature of the returned option makes it impossible to misinterpret the result Java Optional Types It s a joy that finally in Java 8 we ll have a new class called Optional that allows us to implement a similar idiom as that from the functional world As in the case of of SML the Optional type is polymorphic and may contain a value or be empty So we could rewrite our previous code snippet as follows public static Optional Fruit find String name List Fruit fruits for Fruit fruit fruits if fruit getName equals name return Optional of fruit return Optional empty As you can see the method now returns an Optional reference 1 if something is found the Optional object is constructed with a value 4 otherwise is constructed empty 7 And the programmer using this code would do something as follows List Fruit fruits asList new Fruit apple new Fruit grape new Fruit orange Optional Fruit found find lemon fruits if found isPresent Fruit fruit found get String name fruit getName Now it is made evident in the type of the find method that it returns an optional value 5 and the user of this method has to program his code accordingly 6 7 So we see that the adoption of this functional idiom is likely to make our code safer less prompt to null dereferencing problems and as a result more robust and less error prone Of course it is not a perfect solution because after all Optional references can also be erroneously set to null references but I would expect that programmers stick to the convention of not passing null references where an optional object is expected pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected in these cases the correct is to pass an empty array or collection The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced by the API to verify that Quoting an article I reference later about the use of optional objects in the Guava Collections framework Besides the increase in readability that comes from giving null a name the biggest advantage of Optional is its idiot proof ness It forces you to actively think about the absent case if you want your program to compile at all since you have to actively unwrap the Optional and address that case Other Convenient Methods As of the today besides the static methods of and empty explained above the Optional class contains the following convenient instance methods ifPresent Which returns true if a value is present in the optional get Which returns a reference to the item contained in the optional object if present otherwise throws a NoSuchElementException ifPresent Consumer T consumer Which passess the optional value if present to the provided Consumer which could be implemented through a lambda expression or method reference orElse T other Which returns the value if present otherwise returns the value in other orElseGet Supplier T other Which returns the value if present otherwise returns the value provided by the Supplier which could be implemented with a lambda expression or method reference orElseThrow Supplier T exceptionSupplier Which returns the value if present otherwise throws the exception provided by the Supplier which could be implemented with a lambda expression or method reference Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object For instance we may want to use a default fruit value if nothing is found let s say that we would like to use a Kiwi So we could rewrite our previous code like this Optional Fruit found find lemon fruits String name found orElse new Fruit Kiwi getName In this other example the code prints the fruit name to the main output if the fruit is present In this case we implement the Consumer with a lambda expression Optional Fruit found find lemon fruits found ifPresent f System out println f getName This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty Optional Fruit found find lemon fruits Fruit fruit found orElseGet new Fruit Lemon Clearly we can see that these convenient methods simplify a lot having to work with the optional objects So What s Wrong with Optional The question we face is will Optional get rid of null references And the answer is an emphatic no So detractors immediately question its value asking then what is it good for that we couldn t do by other means already Unlike functional languages like SML o Haskell which never had the concept of null references in Java we cannot simply get rid of the null references that have historically existed This will continue to exist and they arguably have their proper uses just to mention an example three valued logic I doubt that the intention with the Optional class is to replace every single nullable reference but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly But ultimately Optional will be just another reference and subject to same weaknesses of every other reference in the language It is quite evident that Optional is not going to save the day How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list From the detractors we hear interesting arguments like The fact that other alternatives exist i e the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability the JSR 305 with annotations like Nullable and NonNull Some would like it to be usable as in the functional world which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell i e pattern matching Others argue about how it is impossible to retrofit preexisting code to use this idiom i e List get Object which will continue to return null And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs by this creating incompatibilities pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class A compelling argument is that if the programmer invokes the get method in an optional object if it is empty it will raise a NoSuchElementException which is pretty much the same problem that we have with nulls just with a different exception So it would appear that the benefits of Optional are really questionable and are probably constrained

    Original URL path: http://blog.informatech.cr/author/edalorzo/ (2015-08-19)
    Open archived version from archive

  • JPA Standard | Informatech CR Blog
    but not to any particular implementation objects of the underlaying provider To gain access to the Hibernate s Session object we can use a special method in the entity manger Session session entityManager unwrap Session class Be warned that at this point we are escaping from the safety of vendor agnostic code In other words if we ever wanted to use another provider like OpenJPA or EclipseLink we would be forced to find a different alternative to implement our code here since those other providers won t offer anything like Hibernate s Session and ScrollableResults From Iterators to Spliterators to Streams Our next step consists in obtaining a Java 8 stream out of this iterator Lukas Eder recently wrote an interesting article about the difficulties to obtain a stream out of an iterable object which will be pretty handy here To achieve our goal we now need to use two utility classes in Java 8 named StreamSupport and Spliterators For instance we could take an iterator like the one we defined above and transform it into a Spliterator by doing private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it StreamSupport stream spliterator false At this point we have built enough to create our first stream out of a JPQL query We can do it as follows public Stream T getResultStream String sql Integer fetchSize Map String Object parameters Query query session createQuery sql if fetchSize null query setFetchSize fetchSize for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue query setReadOnly true ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close A JPA Stream API We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API public interface StreamQuery T Stream T getResultStream StreamQuery T setParameter String name Object value StreamQuery T setFetchSize int fetchSize And putting together all we have learned so far we could create this implementation of our new StreamQuery interface public class HibernateQueryStream T implements StreamQuery T private final Session session private final String sql private final Class T type private final Map String Object parameters new HashMap private Integer fetchSize public HibernateQueryStream EntityManager entityManager String sql Class T type this session entityManager unwrap Session class this sql sql this type type Override public StreamQuery T setParameter String name Object value parameters put name value return this Override public StreamQuery T setFetchSize int fetchSize this fetchSize fetchSize return this Override public Stream T getResultStream Query query session createQuery sql if fetchSize null query setFetchSize fetchSize query setReadOnly true for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type

    Original URL path: http://blog.informatech.cr/tag/jpa-standard/ (2015-08-19)
    Open archived version from archive

  • Functional Programming with Java 8 Functions | Informatech CR Blog
    x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10 Partial Function Application or Currying In most functional programming languages it is possible to create partially applied functions That is if a function is receiving multiple arguments we can partially invoke the function providing just a few arguments and receive a partially applied function

    Original URL path: http://blog.informatech.cr/2014/10/19/functional-programming-with-java-8-functions/ (2015-08-19)
    Open archived version from archive

  • Why There Is Interface Pollution in Java 8 | Informatech CR Blog
    on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive

    Original URL path: http://blog.informatech.cr/2014/04/04/jdk-8-interface-pollution/ (2015-08-19)
    Open archived version from archive

  • function composition | Informatech CR Blog
    add1 makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply

    Original URL path: http://blog.informatech.cr/tag/function-composition/ (2015-08-19)
    Open archived version from archive

  • functional programming | Informatech CR Blog
    add1 makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply

    Original URL path: http://blog.informatech.cr/tag/functional-programming/ (2015-08-19)
    Open archived version from archive

  • high | Informatech CR Blog
    makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10

    Original URL path: http://blog.informatech.cr/tag/high/ (2015-08-19)
    Open archived version from archive