Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Graphs : 59

    • Streams : 58

    • Generics : 57

    • Implementing a Map : 56

    • Hashing : 55

    • Binary Search : 54

    • Quicksort : 53

    • Merge Sort : 52

    • Sorting Algorithms : 51

    • Practice with Recursion : 50

    • Trees and Recursion : 49

    • Trees : 48

    • Recursion : 47

    • Lists Review and Performance : 46

    • Linked Lists : 45

    • Algorithms and Lists : 44

    • Lambda Expressions : 43

    • Anonymous Classes : 42

    • Practice with Interfaces : 41

    • Implementing Interfaces : 40

    • Using Interfaces : 39

    • Working with Exceptions : 38

    • Throwing Exceptions : 37

    • Catching Exceptions : 36

    • References and Polymorphism : 35

    • References : 34

    • Data Modeling 2 : 33

    • Equality and Object Copying : 32

    • Polymorphism : 31

    • Inheritance : 30

    • Data Modeling 1 : 29

    • Static : 28

    • Encapsulation : 27

    • Constructors : 26

    • Objects, Continued : 25

    • Introduction to Objects : 24

    • Compilation and Type Inference : 23

    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Streams

    import java.util.stream.Stream;
    public class Dog {
    private String name;
    public Dog(String setName) {
    name = setName;
    }
    public String getName() {
    return name;
    }
    }
    Stream.of(new Dog("Shadow"), new Dog("Chuchu"), new Dog("Lulu"))
    .map(dog -> dog.getName())
    .sorted()
    .forEach(System.out::println);

    This lesson introduces a new programming paradigm that is particular useful for working with data: streams. We’ll manipulated linear collections of data using good old for loops. But we can do better. Let’s see how!

    Iterative Building Blocks
    Iterative Building Blocks

    Many of the code and algorithms we’ve written together have operated on sequential data, stored in either arrays or Lists. And we’ve seen and identified common patterns for working with this kind of data. Such as counting:

    import java.util.List;
    import java.util.Arrays;
    List<Integer> values = Arrays.asList(1, 2, 5);
    int count = 0;
    for (int value : values) {
    if (value >= 1) {
    count++;
    }
    }
    System.out.println(count);

    And searching:

    import java.util.List;
    import java.util.Arrays;
    List<Integer> values = Arrays.asList(1, 2, 5);
    boolean found = false;
    for (int value : values) {
    if (value == 2) {
    found = true;
    break;
    }
    }
    System.out.println(found);

    And transforming:

    import java.util.List;
    import java.util.Arrays;
    import java.util.ArrayList;
    List<Integer> values = Arrays.asList(1, 2, 5);
    List<String> strings = new ArrayList<>();
    for (int value : values) {
    strings.add("" + value + "ee");
    }
    System.out.println(strings);

    And filtering:

    import java.util.List;
    import java.util.Arrays;
    import java.util.ArrayList;
    List<Integer> values = Arrays.asList(1, 2, 5);
    List<Integer> evens = new ArrayList<>();
    for (int value : values) {
    if (value % 2 == 0) {
    evens.add(value);
    }
    }
    System.out.println(evens);

    And combining:

    import java.util.List;
    import java.util.Arrays;
    List<Integer> values = Arrays.asList(1, 2, 5);
    String combined = "";
    for (int value : values) {
    combined += value;
    }
    System.out.println(combined);

    And while these are fine building blocks for creating larger programs, there is something a bit repetitive and dull about them. Every one has the same overall structure: the same loop, the same return structure. Shouldn’t there be a better, more compact way of expressing these kind of patterns?

    Streams
    Streams

    Yes. There is. And in Java these are called streams.

    Streams allow us to work with sequential data by composing powerful programming primitives to great effect. First, let’s examine the Javadoc together.

    Stream Operations
    Stream Operations

    Next, let’s examine how to utilize common stream operations to replace the repetitive loop-based code we wrote above. First, let’s look at how to set up a stream and one of the most basic stream operations—map:

    // Stream Setup and map

    We can also filter streams using… filter. And count them using… count! Let’s see how:

    // filter

    And, we can even reduce a Stream until a single value with reduce, a surprisingly powerful primitive.

    // reduce

    Why Streams?
    Why Streams?

    Streams may seem alien to you at first. That’s not surprising. A famous silicon valley tech thought leader has pointed out that powerful programming ideas usually feel strange and even bizarre at first. But, as you come to appreciate them, not only do they become more natural, but the older less-powerful ways of doing things start to see even more limited.

    Compared to for loops, Streams are:

    Stream Example
    Stream Example

    To wrap up, let’s have some fun with Streams working with one of our favorite data sets:

    import java.util.stream.Stream;
    public class Dog {
    private String name;
    private int age;
    public Dog(String setName, int setAge) {
    name = setName;
    age = setAge;
    }
    public String getName() {
    return name;
    }
    public int getAge() {
    return age;
    }
    }

    Solve: Escape a Maze

    Created By: Geoffrey Challen
    / Version: 2021.4.0

    Let's get some more practice with algorithms by escaping from a maze! Implement a public class MazeEscape that provides a single public class method named escape. escape accepts a single parameter, a Maze object with methods explained below. Your goal is to manipulate the maze until you reach the exit, and then return it when you are finished. If the passed maze is null, throw an IllegalArgumentException.

    To navigate the maze, using the following Maze methods:

    • isFinished(): returns true when you have reached the exit of the maze
    • turnRight() rotates your character 90 degrees to the right
    • turnLeft() rotates your character 90 degrees to the left
    • canMove() returns true if you can move one cell forward, false otherwise. Your path may be blocked by a wall!
    • move() moves your character one cell forward and increases the step counter

    The passed Maze object represents a simply-connected or perfect maze: one that contains no loops. As a result, we suggest that you pursue a classic maze escape algorithm: wall following. Simply put, in a maze that contains no loops, as long as you continue following a wall you will eventually reach the exit. In a corn maze, you might implement this by simply maintaining contact with a wall (right or left) until you complete the maze. However, you'll need to think a bit about how to implement this algorithm to finish this problem.

    More Practice

    Need more practice? Head over to the practice page.