This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Features new in Java 8 and the fly likes Pattern Matching Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Features new in Java 8
Bookmark "Pattern Matching" Watch "Pattern Matching" New topic
Author

Pattern Matching

Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 337

Does Java 8 include pattern matching?
Ulf Dittmer
Rancher

Joined: Mar 22, 2005
Posts: 42954
    
  73
What do you mean, exactly? Java has long included an API for regular expressions, which can be used for pattern matching.
Tim Cooke
Bartender

Joined: Mar 28, 2008
Posts: 1576
    
  85

I think he means pattern matching as is common in functional languages. Scala for example:


Tim Driven Development
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10385
    
174

Haven't used Scala. Out of curiosity, what is that code example meant to do? To me it looks like equivalent to a switch case in Java:


Although, I don't see how that relates to pattern matching.

[My Blog] [JavaRanch Journal]
Tim Cooke
Bartender

Joined: Mar 28, 2008
Posts: 1576
    
  85

It is equivalent to a switch statement in Java but a good deal more flexible. Your example was close but you didn't include the default option

The example looks a bit trivial when matching with String but it becomes more powerful when you start matching on more complex types such as a List:

Or some custom type:
Piet Souris
Ranch Hand

Joined: Mar 08, 2009
Posts: 728
    
  11
In the Scala course at Coursera I wrote the following code, to see if I got
everything correct:



Greetz,
Piet
Richard Reese
author
Ranch Hand

Joined: Jul 13, 2011
Posts: 84
    
    5

Will,

The first thing that came to my head was how lambda expressions are “matched” with a functional interface. While this is probably not exactly what you are asking about, it is an interesting and powerful feature of Java 8. Also, the PathMatcher interface came to mind. This was added in Java 1.7 but I do include an example of how it can be used with lambda expressions in the book.

Richard Reese
Java 8 New Features: A Practical Heads-Up Guide
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Pattern Matching