Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Stream - Does this seem correct or is there a better way?

 
C. Raymond Carroll
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just now learning how to use Java 8 Stream and Lambda and was hoping one of the experts could take a look and tell me if there is a better way.

I have a List that may or may not return an element (Region) and if there is no Region I want to return an empty one.

Thanks,
Raymond


public Region getRegionByAbbrv(String strAbbrv) {

TypedQuery<Region> queryRegion = em.createNamedQuery("Region.findByAbbrv",Region.class);

queryRegion.setParameter("abbrv", strAbbrv);
queryRegion.setMaxResults(1);


return queryRegion.getResultList()
.stream()
.filter(p -> p !=null)
.findFirst()
.orElse(new Region());


}
 
Piet Souris
Rancher
Posts: 1641
36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
looks fine to me. A simple

would also do, especially in a Java < 8 environment.

Greetz,
Piet
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15715
73
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also write this line:
C. Raymond Carroll wrote:.filter(p -> p !=null)

like this:
 
Rob Spoor
Sheriff
Posts: 20822
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd put the filter in the SQL query. After that it would be simply checking if getResultList() returns an empty list. However, you should only call getResultList() once; each time you call it, the query gets executed.
 
C. Raymond Carroll
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the suggestions

Regards,
Raymond
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!