wood burning stoves
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Features new in Java 8
Bookmark "Pattern Matching" Watch "Pattern Matching" New topic

Pattern Matching

Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 370

Does Java 8 include pattern matching?
Ulf Dittmer

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

Joined: Mar 28, 2008
Posts: 2534

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

Tim Driven Development
Jaikiran Pai

Joined: Jul 20, 2005
Posts: 10441

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

Joined: Mar 28, 2008
Posts: 2534

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: 982
In the Scala course at Coursera I wrote the following code, to see if I got
everything correct:

Richard Reese
Ranch Hand

Joined: Jul 13, 2011
Posts: 84


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
It's not a secret anymore!