This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez 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 Soft Skills this week in the Jobs Discussion 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: 331

Does Java 8 include pattern matching?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42906
    
  69
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: 1217
    
  67

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: 10285
    
169

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: 1217
    
  67

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: 700
    
  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