Java - How to use functions in a stream?

Related searches

Recently, as part of my studies, we started practicing Java problem solving with streams. While solving quantitative problems of add / subtract or string / character sorting problems with streams, relatively clear and understandable, however, a little more complicated problems are not clear to me with the use of streams.

For example, given a set of characters, we must print for each letter within the range G-O / g-o the inverse signal, such as A becomes Z, and the letter b becomes y.

For example, suppose we had the collection 'A','k','p' - > After the operation we will only get p.

Using simple functions, I was able to solve the problem as follows:

public static char flipLetter(char c){
    int count = 7;
    if((int)c >= 72 && (int)c <= 78){
        for (int i = 72; i <= 78; i++) {
            if((int)c == i)
                return (char)((int)'Z' - count);
            count++;
        }
    }
    else{
        for (int i = 104; i <= 110; i++) {
            if((int)c == i)
                return (char)((int)'z' - count);
            count++;
        }
    }
    return c;
}
public static boolean isInRange(char c){
    return (((int)c >= 72 && (int)c <= 78) || ((int)c >= 104 && (int)c <= 110));

}
public static void inRange(char arr[]){
    for (int i = 0; i < arr.length; i++) {
        if(isInRange(arr[i])){
            System.out.print(flipLetter(arr[i])+" ");
        }
    }
}

I'd be happy to get help on how I can use the code I wrote to implement it with streams, or hear other reviews.

You should try to write code documenting the intent to the reader. So when the task includes the condition "for each letter within the range G-O / g-o", don’t write code like

public static boolean isInRange(char c) {
    return (((int)c >= 72 && (int)c <= 78) || ((int)c >= 104 && (int)c <= 110));
}

Write

public static boolean isInRange(char c) {
    return c > 'G' && c < 'O' || c > 'g' && c < 'o';
}

which makes it immediately obvious that you’re talking about the range "G-O / g-o (exclusive)" rather than "H-N/h-n (inclusive)", not to speak about the unnecessary use of unicode/ascii numbers instead of writing char constants. The code will still do the same, but now, you can recognize the original task in it. The type casts are unnecessary in either variant.

As hinted by Andreas in this comment, you don’t need a counting loop for finding a difference, that’s what minus is for. So flipLetter simplifies to

    if(c > 'G' && c < 'O') {
        return (char)('Z' - (c - 'A'));
    }
    if(c > 'G' && c < 'O') {
        return (char)('z' - (c - 'a'));
    }

but when we use this after the range has been checked already, we can express the intent of differentiating between upper case and lower case directly, using Character.isUpperCase(…) or Character.isLowerCase(…).

Further, basic arithmetic rules tell us that 'Z' - (c - 'A') is the same as ('Z' + 'A') - c, likewise for the lower case variant, so the code for the two cases only differs in a single constant value.

Putting these findings into a Stream operation yields

public static void yourTask(char[] arr) {
    CharBuffer.wrap(arr).chars()
        .filter(c -> c >= 'H' && c <= 'N' || c >= 'h' && c <= 'n')
        .map(c -> (Character.isUpperCase(c)? 'A'+'Z': 'a'+'z') - c)
        .forEachOrdered(ch -> System.out.print((char)ch+" "));
}

(A method name like inRange sounds like a test, so you should come up with a better name describing what the method actually does)

Note that this uses IntStream, as there is no CharStream in Java, which is fine as in Java, calculations involving char values are done using int anyway. Only at the final printing statement, we need to perform a type cast to char, to establish the right semantic, which affects the way, the value is printed.

A Guide to Java Streams in Java 8: In-Depth Tutorial With Examples, forEach() is simplest and most common operation; it loops over the stream elements, calling the supplied function on each element. The method� Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

You could do:

public static void inRange(char arr[]){
    IntStream.range(0, arr.length).mapToObj(i -> arr[i])
             .filter(letter -> isInRange(letter))
             .map(letter -> flipLetter(letter))
             .forEach(e -> System.out.print(e  + " "));
}

Which will create a Stream of the Array passed, filter out any that are not in range, call the flipLetter method on each letter, and then print each out

Java 8 Stream Tutorial, Learn Java 8 streams by example: functional programming with filter, map, with Java 8 streams and how to use the different kind of available stream operations. A function is stateless when the execution of the operation is� For terminal operations, we simple use the forEach operation that print out the current element in the result stream. 1. Java Stream filter operation example. The filter () operation returns a new stream that consists elements matching a given condition which is typically a boolean test in form of a Lambda expression.

One solution for the inRange() method would be this:

public static void inRange(char[] arr) {
    IntStream.range(0, arr.length)
            .mapToObj(i -> arr[i])
            .filter(YourClass::isInRange)
            .map(YourClass::flipLetter)
            .forEach(c -> System.out.print(c + " "));
}

If you want the result as String you can use this:

public static void inRange(char[] arr) {
    String result = IntStream.range(0, arr.length)
            .mapToObj(i -> arr[i])
            .filter(YourClass::isInRange)
            .map(YourClass::flipLetter)
            .map(String::valueOf)
            .collect(Collectors.joining(" "));
    System.out.println(result);
}

If you have a String as input, where you get the char[] from just pass that to the method ans use string.chars() instead of IntStream.range(0, arr.length).

Stream In Java, Introduced in Java 8, the Stream API is used to process collections of objects. A stream of the results of applying the given function to the elements of this stream. //a simple program to demonstrate the use of stream in java. To be more precise, Java’s map method takes a Function such as (sale) -> sale.getPrice () and applies the Function to each value in a stream. So the map method takes an incoming stream of sale objects and creates an outgoing stream of price values.

How to apply a function on each element of a List in Java, How to apply a function on each element of a List in Java. [CG]BOUGA. 10.7K views. 1. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 28. // {. List<Integer> integers� With Java 8, We have a powerful Stream API map () method that help us transform or convert each element of stream with more readable code: <R> Stream<R> map(Function<? super T, ? extends R> mapper); -> It returns a stream consisting of the results of applying the given function to the elements of this stream.

Stream.reduce () in Java with examples. Last Updated: 16-10-2019. Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.

The best option you have is to apply the map to your stream. which returns a stream consisting of the results of applying the given function to the elements of the stream.

Comments
  • Use filter and map, and then collect the stream using Collectors.joining(" ") to get the final string.
  • When you say "we must print for each letter within the range G-O / g-o" do you mean "we must print for each letter NOT within the range G-O / g-o"?
  • @Ray Toal I mean thatif the letter isn't at the range metion above we won't print it at all.
  • Do you want just the inRange() method using a stream, or all methods?
  • FYI: Your flipLetter method is overly complicated, it can be simplified to if (c >= 'H' && c <= 'N') { return (char)('Z' - (c - 'A')); } if (c >= 'h' && c <= 'n') { return (char)('z' - (c - 'a')); } return c;