Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
How to print out an object if it's created with lambda?

Here is my interface example

public interface Card {
    String name();
}

I use it in ArrayList and create objects like this.

public static void main(String[] args) {
    List<Card> cards = new ArrayList<>();
    cards.add(() -> "2");
  cards.add(() -> "4");
    System.out.println(cards);
}

How can I print a number to console if I create an object like this? Here is the example of the printed text.

[d$$Lambda$14/0x0000000800bb1438@2d98a335]

But I want 2 and 4 to be printed out.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try this.

public interface Card {
    String name();

    static Card of(Supplier<String> supplier) {
        return new Card() {
            @Override public String name() { return supplier.get(); }
            @Override public String toString() { return name(); }
        };
    }
}

public static void main(String[] args) {
    List<Card> cards = new ArrayList<>();
    cards.add(Card.of(() -> "2"));
    cards.add(Card.of(() -> "4"));
    System.out.println(cards);
}

output:

[2, 4]

Note: You can't override toString() method.

public interface Card {
    String name();

    public default String toString() {  // compile error
                                        // "A default method cannot override a method from java.lang.Object "
        return name();
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!