I'm trying to write a lambda expression that sorts a string array by string length by using a single lambda expression variable. This is what I have come up with (using two)
public static void main(String[] args) {
Consumer<String[]> sort = s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length());
Consumer<String[]> print = sort.andThen(s -> System.out.println(Arrays.toString(s)));
print.accept(strings);
}
Is there a way to combine sort and print so that they are just one expression? I have tried this:
Consumer<String[]> print = (s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length())).andThen(s -> System.out.println(Arrays.toString(s)));
But I'm just getting
String s1, String s2) -> s1.length() - s2.length()
marked red saying "Cannot infer functional interface type". Is what I'm trying even possible? I know it's a pretty useless this worrying about but now I'm curious if this is possible.
Lambdas in Java always need to target a functional interface (an interface with only a single abstract method). In your case, that is the Consumer-interface.
The reason you get the error when you chain the two lambdas together with andThen is because the compiler doesn't know which functional interface the first lambda is targetting. So it doesn't know which andThen function to call. It only knows that the whole expression should result in a Consumer.
To fix it, you would need to cast the first lambda to Consumer<String[]>. Like this:
Consumer<String[]> print = ((Consumer<String[]>) s -> Arrays.sort(s, (String s1, String s2) -> s1.length() - s2.length()))
.andThen(s -> System.out.println(Arrays.toString(s)));
This can be done using :
Arrays.stream(s).sorted(Comparator.comparingInt(String::length))
.forEach(System.out::println);
Related
I am working on a codewars problem, here is what my code looks like
public static String longest (String s1, String s2) {
// your code
return (s1+s2)
.chars()
.distinct()
.sorted()
.map(i -> String.valueOf(i))
.collect(Collectors.joining());
}
I am getting the following error
Main.java:24: error: incompatible types: bad return type in lambda
expression
.map(i -> String.valueOf(i))
^
String cannot be converted to int
can someone explain to mo why I am getting the error and how to fix it?
String.chars returns an IntStream and not a Stream<Character> or Stream<Integer>. The map method on IntStream requires an IntUnaryOperator, which is basically a function that takes an int and returns another int. Therefore, the compiler expected your lambda expression in the call to map to return an int instead of a String.
What you want is mapToObj which takes an int and turns it into an object of some kind (in this case, a String).
Assuming you want to return a string made of the distinct chars of the prameters passed, you could split the concatenated string at each char and collect all distinct back to string, i.e something like:
public static String foo(String s1, String s2){
return Pattern.compile("")
.splitAsStream(s1+s2)
.distinct()
.sorted()
.collect(Collectors.joining());
}
or if you want to stick to your first aproach, you can use StringBuilder or StringWriter to build a string with your distinct chars
public static String foo1(String s1, String s2){
return (s1+s2).chars()
.distinct()
.sorted()
.collect(StringBuilder::new, (sb, c) -> sb.append((char) c),StringBuilder::append)
.toString();
}
I have some stream handling code that takes a stream of words and performs some operations on them, then reduces them to a Map containing the words as keys and the number of occurrences of the word as a Long value. For the sake of the brevity of the code, I used the jOOL library's Seq class, which contains a number of useful shortcut methods.
The code compiles just fine if I write it like this:
item.setWordIndex (
getWords (item) // returns a Seq<String>
.map (this::removePunctuation) // String -> String
.map (stemmer::stem) // String -> String
.groupBy(str -> str, Collectors.counting ()));
However, if I attempt to replace the str -> str lambda with the more self-documenting Function::identity, I get the following errors:
The method setWordIndex(Map<String,Long>) in the type MyClass is not applicable for the arguments (Map<Object,Long>)
The type Function does not define identity(String) that is applicable here
Why does Function::identity behave any differently to str -> str, which I (perhaps naively) assumed was directly equivalent, and why can't the compiler handle it when it is used?
(And yes, I'm aware I could remove the identity function by moving the previous map application into the groupBy operation, but I find the code clearer like this, because it follows the application logic more directly)
You want Function.identity() (which returns a Function<T, T>), not Function::identity (which matches the SAM type Supplier<Function<T, T>>).
The following code compiles fine:
static String removePunctuation(String x) { return x; }
static String stem(String x) { return x; }
// ...
final Map<String, Long> yeah = Seq.of("a", "b", "c")
.map(Test::removePunctuation)
.map(Test::stem)
.groupBy(Function.identity(), Collectors.counting());
There is a slight difference between the two types; they are not directly equivalent:
Function.identity() has to return the input type, because its type is Function<T, T>;
str -> str can return a wider type; effectively it is Function<? extends T, T>.
lets say we a Predicate and a Function-Interface:
Function<String, String> function = null;
Predicate<String> predicate = null;
Now I want to give the Predicate-Interface a method reference where the return type is a boolean and in our case the parameter a string. But why the following method reference seems to be right:
Predicate<String> predicate = String::isEmpty;
The isEmpty-method has no String-Parameter,although the Predicate-Interface requires a String-Parameter. Why it is still right? Am I missing something?
Another Example: The Function interface returns in our case a String and takes a String as parameter. But the following method reference seems to be wrong:
Function<String, String> function = String::concat; //wrong
The Concat-Method has a String as Parameter and returns a String. Why its wrong?
Hopefully somebody can explain it to me.
When you use a method reference on an instance method, the method receiver becomes the first argument. So
String::isEmpty
is equivalent to
(String str) -> str.isEmpty()
and
String::concat
is equivalent to
(String a, String b) -> a.concat(b)
...which does not match the type of Function.
The reason why
Function<String, String> function = String::concat;
does not compile is because it is equivalent to (as Louis written)
Function<String, String> function = (String a, String b) -> a.concat(b);
while Function.apply(T t) takes only one argument (t) and you are passing a function that takes two arguments (a and b).
String::isEmpty can, in theory, mean one of two things.
A static method in the String class:
s -> String.isEmpty(s)
An instance method in the String class:
(String s) -> s.isEmpty()
Your case falls into #2.
Similarly, String::concat can mean one of two things:
(s1, s2) -> String.concat(s1, s2)
or
(String s1, String s2) -> s1.concat(s2) // Your case
(However, this is not a Function<String, String>, as it does not take precisely one argument. It is, however, a BinaryOperator<String>.)
Using the Java Stream API, is there a way to do additional processing to adjust the value of whatever is passed to a method reference?
I'll give two examples.
Example 1.
In the first example, I start with a Stream<Path>, and I want to return a Map<String, Path> in which the keys in the map are processed version of the filename using another function that takes a String filename (not a Path). Specifically:
public Map<String, Path> createMap(Path sourceFolder, PathMatcher filter) {
return stream.filter(filter::matches)
.collect(Collectors.toMap(FilenameHelper::parseFilename, Function.identity()));
parseFilename(String filename) takes a String filename, but of course the method reference gets a Path. I'd like to say something like, FilenameHelper::parseFilename(((Path)Function.identity()).toFile().getName()) but that doesn't work (Eclipse says: "The left-hand side of an assignment must be a variable"). I can work around it by creating a new method that takes a Path and just does return parseFilename(path.toFile().toName()) but that's not cool.
Example 2.
In the second example, I have rows, a List<List<String>>> that represents a data table (rows, then columns). I have a method that should return a List<String> consisting of a specific column in that table for every nth row. I want to do something like:
public List<String> getDataFromColumn(String columnName, int nth) {
/// Without a clause at ???, this returns a List<List<String>>
return IntStream.range(0, rows.size())
.filter(n -> n % nth == 0) // Get every nth row
.mapToObj(rows::get)
.???
.collect(Collectors.toList());
}
Where "???" should be something like map(ArrayList::get(headers.indexOf(columnName))) (where headers is a List<String> containing the column headers) but if I put that in, I get an AssignmentOperator syntax error in the get part of this clause. Replacing map with forEach doesn't help here. In other words, I don't want rows.get(n), I want rows.get(n).get(headers.indexOf(columnName).
Question
In both of these examples, I want to do something additional to the value that is being passed to the method pointed to with the method reference operator (::). Is there a "Java Stream-ic" way to do additional processing to the thing being passed to the method reference?
Method references are essentially a convenient substitute for lambdas where the function signature is an exact match to the method signature. In your case you can just use regular lambdas:
public Map<String, Path> createMap(Path sourceFolder, PathMatcher filter) {
return stream.filter(filter::matches)
.collect(Collectors.toMap(path -> FilenameHelper.parseFilename(path.toFile().getName()), Function.identity()));
}
public List<String> getDataFromColumn(String columnName, int nth) {
return IntStream.range(0, rows.size())
.filter(n -> n % nth == 0)
.mapToObj(rows::get)
.map(row -> row.get(headers.indexOf(columnName)))
.collect(Collectors.toList());
}
How about Function.compose? Of course you cannot use FilenameHelper::parseFilename.compose, but you can easily write a static helper method to work around it:
static <T, V, R> Function<T, R> compose(Function<T, V> f, Function<V, R> g) {
return g.compose(f);
}
Now we can compose method references:
return stream.filter(filter::matches)
.collect(Collectors.toMap(
compose(
compose(Path::getFileName, Path::toString),
FilenameHelper::parseFilename),
Function.identity()));
This is actually not very readable but an alternative to writing a full lambda.
No, this functionality is currently not provided.
The usual way would be to just not use a method reference and instead call the method the "usual" way using a lambda expression:
stream.filter(filter::matches)
.collect(Collectors.toMap(p -> FilenameHelper.parseFilename(p.getFileName()), Function.identity()));
No, there is not. There is no syntax to do that.
And if you wanted such a thing then lambda expression is what you want.
Method reference or lambda, under the hood you are still going to get a class that actually implements the Predicate/Function so it does not matter.
And that argument but that's not cool, to me under the conditions that there is no syntax for that, it's the best option you have.
Underneath the actual calls that you there is a MethodHandle (introduced in jdk-7) and MethodHandles do not have a way to achieve what you want. I think the same restriction exists in C++ with method pointers.
This title sounds stupid even to me, but there must be at least somewhat clever way to achieve such effect and I don't know how else to explain it. I need to sort array using sorted in stream API. Here is my stream so far:
Arrays.stream(sequence.split(" "))
.mapToInt(Integer::parseInt)
.boxed()
.sorted((a, b) -> a.compareTo(b))
.forEach(a -> System.out.print(a + " "));
Now I have two different sorts of course - ascending and descending and the sort I need to use is specified in the user input. So what I want to do is having something like switch with 2 cases: "ascending" and "descending" and a variable to store the lambda expression respectively:
switch(command) {
case "ascending": var = a.compareTo(b);
case "descending": var = b.compareTo(a);
}
Then I my sorted looks like:
.sorted((a, b) -> var)
I got the idea in a python course I attended. There it was available to store an object in variable, thus making the variable "executable". I realize that this lambda is not an object, but an expression, but I'm asking is there any clever way that can achieve such result, or should I just have
if(var)
and two diferent streams for each sort order.
The question is not stupid at all. Answering it in a broader sense: Unfortunately, there is no generic solution for that. This is due to the type inference, which determines one particular type for the lambda expression, based on the target type. (The section about type inference may be helpful here, but does not cover all details regarding lambdas).
Particularly, a lambda like x -> y does not have any type. So there is no way of writing
GenericLambdaTypefunction = x -> y;
and later use function as a drop-in replacement for the actual lambda x -> y.
For example, when you have two functions like
static void useF(Function<Integer, Boolean> f) { ... }
static void useP(Predicate<Integer> p) { ... }
you can call them both with the same lambda
useF(x -> true);
useP(x -> true);
but there is no way of "storing" the x -> true lambda in a way so that it later may be passed to both functions - you can only store it in a reference with the type that it will be needed in later:
Function<Integer, Boolean> f = x -> true;
Predicate<Integer> p = x -> true;
useF(f);
useP(p);
For your particular case, the answer by Konstantin Yovkov already showed the solution: You have to store it as a Comparator<Integer> (ignoring the fact that you wouldn't have needed a lambda here in the first place...)
You can switch between using Comparator.reverseOrder() and Comparator.naturalOrder:
Comparator<Integer> comparator = youWantToHaveItReversed ? Comparator.reverseOrder(): Comparator.naturalOrder();
Arrays.stream(sequence.split(" "))
.map(Integer::valueOf)
.sorted(comparator)
.forEach(a -> System.out.print(a + " "));
In Lambdas you can use a functionblock
(a,b) -> { if(anything) return 0; else return -1;}