Java8 Exercises
Java8 Exercises
2. Make a method called betterString that takes two Strings and a lambda
that says whether the first of the two is “better”. The method should
return that better String; i.e., if the function given by the lambda
returns true, the betterString method should return the first String,
otherwise betterString should return the second String. Here are two
examples of how your code should work when it is finished (the first
lambda example returns whichever of string1 and string2 is longer, and
the second lambda example always returns string1).
• String string1 = ...;
• String string2 = ...;
• String longer = StringUtils.betterString(string1, string2,
(s1, s2) -> s1.length() > s2.length());
• String first = StringUtils.betterString(string1, string2,
(s1, s2) -> true);
Accomplishing all of this requires you to do three things:
• Define the TwoStringPredicate interface. It will specify a method
that takes 2 strings and returns a boolean.
• Define the static method betterString. That method will take 2
strings and an instance of your interface. It returns string1 if the
method in interface returns true, string2 otherwise.
• Call betterString.
3. Use generics to replace your String-specific solutions to problem 3
with generically typed solutions. That is, replace betterString with
betterEntry and TwoStringPredicate with TwoElementPredicate. Make
sure your previous examples still work when you only change
betterString to betterElement. But, now you should also be able to
supply two Cars and a Car predicate, two Employees and an Employee
predicate, etc. For example:
• ElementUtils.betterElement(string1, string2,
(s1, s2) -> s1.length() > s2.length())
• ElementUtils.betterElement(car1, car2,
(c1, c2) -> c1.getPrice() > c2.getPrice())
• ElementUtils.betterElement(employee1, employee2,
(e1, e2) -> e1.getSalary() > e2.getSalary())
For all the exercises, start with a List of Strings similar to this:
• List<String> words = Arrays.asList("hi", "hello", ...);
9. Loop down the words and print each on a separate line, with two
spaces in front of each word. Don’t use map.
10. Repeat the previous problem, but without the two spaces in front. This
is trivial if you use the same approach as in #9, so the point is to use a
method reference here, as opposed to an explicit lambda in problem 9.
15. Produce the same String as above, but this time via a map operation
that turns the words into upper case, followed by a reduce operation
that concatenates them.
16. Produce a String that is all the words concatenated together, but with
commas in between. E.g., the result should be "hi,hello,...". Note that
there is no comma at the beginning, before “hi”, and also no comma at
the end, after the last word.
17. Find the total number of characters (i.e., sum of the lengths) of the
strings in the List.