PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How do I compare values of an Object with the StreamAPI and Lambda expressions?

 November 04, 2022     collections, java, java-stream, lambda     No comments   

Issue

I got a problem with streams. I'm trying to compare everything in my LinkedList to get the latest Medium with the StreamAPI. The problem I run into is that my methode sucheNeuesMedium() throws NoSuchElementExeption, because get() finds no value. The stream is filled with elements (befor anyone says "be sure that you got objects in your list"). I want to compare them by the value of "Jahr" (it has to be with the StreamAPI and Lambda expressions). Any ideas how I can make this run? If you need further information I will supply you.

    //In class Medienverwaltung
    LinkedList<Medium> liste = new LinkedList<Medium>();
    Iterator<Medium> it = liste.iterator(); //irrelevant for this task
    Stream<Medium> stream = liste.stream();

    public Medium sucheNeuesMedium() {
        return stream.max(Comparator.comparing(Medium::getJahr)).get();
    }

    //In abstract class Medium
    public int getJahr() {
        return jahr;
    }

Solution

I found my error: I have to operate with liste.stream() and then my comparison. I always tried it on Imported objects (serialized), meaning the stream stayed empty (the stream got initialized with the empty list). But if I use liste.stream().max(Comparator.comparing(Medium::getJahr)).get(); it works flawless and multiple times not once. I didn't think about the stream being used aswell. It works, but still thanks for the fast answers.



Answered By - Hristian
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing