How to print streamex on the console

64 views Asked by At

i try to print all elements of the streamex on the console, but I get always this issue

one.util.streamex.StreamEx@2e817b38

So I call "convert" method from the main, but i doesn't work.. Do you have any idea, how can I make it right?

enter image description here

I hope to get helpful answer for my question.

1

There are 1 answers

0
sanurah On

Please post your code it's hard to read the screenshot. From your output it seems you are printing the StreamEx object from convert method. That will not output what you need.

When you print a java object it invokes toString() method which all Objects inherit. By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.

This is why you get an output like this,

one.util.streamex.StreamEx@2e817b38

First you need to iterate the StreamEx stream and then print the object. Notice that in Racer class toString method is overridden. So when we call print on racer object it will invoke toString() method that we have written.

import java.util.ArrayList;
import java.util.List;
import one.util.streamex.StreamEx;

class PopupMenuExample {
    
    public static void main(String args[]) {

        StreamEx<Racer> racerStream = convert();
        System.out.println("this is wrong: " + racerStream);

        System.out.println("this is correct: ");
        racerStream.forEach(
                racer -> {
                    System.out.println(racer);
                }
        );
    }

    private static StreamEx<Racer> convert() {
        Racer r1 = new Racer("one", 40);
        Racer r2 = new Racer("two", 100);
        List<Racer> racers = new ArrayList<>();
        racers.add(r1);
        racers.add(r2);
        return StreamEx.of(racers);
    }
}

class Racer {
    String name;
    Integer speed;

    public Racer(String name, Integer speed) {
        this.name = name;
        this.speed =speed;
    }

    @Override
    public String toString() {
        return String.format("{ name:%s, speed: %d }", name, speed);
    }
}

Output:

this is wrong: one.util.streamex.StreamEx@7229724f

this is correct: { name:one, speed: 40 } { name:two, speed: 100 }