SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Productive Programming with
Groovy
S G Ganesh
http://ocpjp7.blogspot.in
Introducing Groovy
How I Felt Programming in Groovy vs.
Java!
Simple (first) Example
import java.io.*;
class Type {
public static void main(String []files) {
// process each file passed as argument
for(String file : files) {
// try opening the file with FileReader
try (FileReader inputFile = new FileReader(file)) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
} catch (FileNotFoundException fnfe) {
System.err.printf("Cannot open the given file %s ", file);
}
catch(IOException ioe) {
System.err.printf("Error when processing file %s; skipping it", file);
}
// try-with-resources will automatically release FileReader object
}
}
}
args.each { println new File(it).getText() }
Mere Syntactic Sugar?
Map<String, String> inglishWords = new HashMap<>();
inglishWords.put("Shampoo", "'Chapmo' (Hindi)");
inglishWords.put("Sugar", "'Sarkkarai' (Tamil)");
inglishWords.put("Copra", "'Koppara' (Malayalam)");
inglishWords.put("Jute", "'Jhuto' (Bengali)");
inglishWords.put("Cot", "'Khatva' (Sanskrit)");
for(Map.Entry<String, String> word : inglishWords.entrySet()) {
System.out.printf("%s => %s n", word.getKey(), word.getValue());
}
def inglishWords = [ "Shampoo" : "'Chapmo' (Hindi)",
"Sugar" : "'Sarkkarai' (Tamil)",
"Copra" : "'Koppara' (Malayalam)",
"Jute" : "'Jhuto' (Bengali)",
"Cot" : "'Khatva' (Sanskrit)" ]
inglishWords.each {
key, value ->
println "$key => $value"
}
Just Concise Expression?
System.out.println("The (key-based) sorted map is: ");
Map<String, String> keySortedMap = new TreeMap<>(inglishWords);
for(Map.Entry<String, String> word : keySortedMap.entrySet()) {
System.out.printf("%s => %s n", word.getKey(), word.getValue());
}
println "The (key-based) sorted map is: "
def keySortedMap = inglishWords.sort()
keySortedMap.each {
key, value ->
println "$key => $value"
}
Now for the Real Magic! 
class MapUtil {
// this code segment from http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
{
return (o1.getValue()).compareTo( o2.getValue() );
}
} );
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
}
System.out.println("The (value-based) sorted map is: ");
Map<String, String> valueSortedMap = MapUtil.sortByValue(inglishWords);
for(Map.Entry<String, String> word : valueSortedMap.entrySet()) {
System.out.printf("%s => %s n", word.getKey(), word.getValue());
}
println "The (value-based) sorted map is: "
def valueSortedMap = inglishWords.sort { it.value }
valueSortedMap.each {
key, value ->
println "$key => $value"
}
HTML Creation Example
try (PrintWriter pw = new PrintWriter(new FileWriter("./index.java.html"))) {
pw.println("<html> <head> <title>Words from Indian origin in English</title> </head>
<body>");
pw.println("<h1>Words from Indian origin in English</h1>");
pw.println("<table border='1'> <tr> <th>Inglish word</th> <th>Origin</th></tr>");
for(Map.Entry<String, String> word : inglishWords.entrySet()) {
pw.printf("<tr> <td> %s </td> <td> %s </td> </tr>", word.getKey(),
word.getValue());
}
pw.println("</table> <p style='font-style:italic;font-size:small;float:right'>Results obtained at
" + new Date() + "</p> </body> </html>");
}
HTML Creation Example
def writer = new StringWriter()
def doc = new MarkupBuilder(writer)
doc.html() {
head {
title("Words from Indian origin in English")
}
body {
h1("Words from Indian origin in English")
table(border:1) {
tr {
th("Inglish word")
th("Origin")
}
inglishWords.each { word, root ->
tr {
td("$word")
td("$root")
}
}
}
p(style:'font-style:italic;font-size:small;float:right', "Results obtained at ${new Date().dateTimeString}")
}
}
def filename = 'index.groovy.html'
new File(filename).write(writer.toString())
Not Convinced?! Check XML Creation
Example
try (PrintWriter pw = new PrintWriter(new FileWriter("./words.xml"))) {
pw.println("<inglishwords>");
for(Map.Entry<String, String> word : inglishWords.entrySet()) {
pw.printf("t<language word='%s'> n tt <origin>
'%s'</origin> n t </language> n", word.getKey(), word.getValue());
}
pw.println("</inglishwords>");
}
xmlbuilder = new groovy.xml.MarkupBuilder()
xmlbuilder.inglishwords {
words.each { key, value ->
language(word:key) { origin(value) }
}
}
Where to Learn More About Groovy?
Some Dynamic Languages for .NET
World

Weitere Àhnliche Inhalte

Mehr von Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by ExampleGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - QuizGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 

Mehr von Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 

KĂŒrzlich hochgeladen

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

KĂŒrzlich hochgeladen (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Productive programming with groovy - an introduction

  • 1. Productive Programming with Groovy S G Ganesh http://ocpjp7.blogspot.in
  • 3. How I Felt Programming in Groovy vs. Java!
  • 4. Simple (first) Example import java.io.*; class Type { public static void main(String []files) { // process each file passed as argument for(String file : files) { // try opening the file with FileReader try (FileReader inputFile = new FileReader(file)) { int ch = 0; while( (ch = inputFile.read()) != -1) { // ch is of type int - convert it back to char System.out.print( (char)ch ); } } catch (FileNotFoundException fnfe) { System.err.printf("Cannot open the given file %s ", file); } catch(IOException ioe) { System.err.printf("Error when processing file %s; skipping it", file); } // try-with-resources will automatically release FileReader object } } } args.each { println new File(it).getText() }
  • 5. Mere Syntactic Sugar? Map<String, String> inglishWords = new HashMap<>(); inglishWords.put("Shampoo", "'Chapmo' (Hindi)"); inglishWords.put("Sugar", "'Sarkkarai' (Tamil)"); inglishWords.put("Copra", "'Koppara' (Malayalam)"); inglishWords.put("Jute", "'Jhuto' (Bengali)"); inglishWords.put("Cot", "'Khatva' (Sanskrit)"); for(Map.Entry<String, String> word : inglishWords.entrySet()) { System.out.printf("%s => %s n", word.getKey(), word.getValue()); } def inglishWords = [ "Shampoo" : "'Chapmo' (Hindi)", "Sugar" : "'Sarkkarai' (Tamil)", "Copra" : "'Koppara' (Malayalam)", "Jute" : "'Jhuto' (Bengali)", "Cot" : "'Khatva' (Sanskrit)" ] inglishWords.each { key, value -> println "$key => $value" }
  • 6. Just Concise Expression? System.out.println("The (key-based) sorted map is: "); Map<String, String> keySortedMap = new TreeMap<>(inglishWords); for(Map.Entry<String, String> word : keySortedMap.entrySet()) { System.out.printf("%s => %s n", word.getKey(), word.getValue()); } println "The (key-based) sorted map is: " def keySortedMap = inglishWords.sort() keySortedMap.each { key, value -> println "$key => $value" }
  • 7. Now for the Real Magic!  class MapUtil { // this code segment from http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet() ); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) { return (o1.getValue()).compareTo( o2.getValue() ); } } ); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } } System.out.println("The (value-based) sorted map is: "); Map<String, String> valueSortedMap = MapUtil.sortByValue(inglishWords); for(Map.Entry<String, String> word : valueSortedMap.entrySet()) { System.out.printf("%s => %s n", word.getKey(), word.getValue()); } println "The (value-based) sorted map is: " def valueSortedMap = inglishWords.sort { it.value } valueSortedMap.each { key, value -> println "$key => $value" }
  • 8. HTML Creation Example try (PrintWriter pw = new PrintWriter(new FileWriter("./index.java.html"))) { pw.println("<html> <head> <title>Words from Indian origin in English</title> </head> <body>"); pw.println("<h1>Words from Indian origin in English</h1>"); pw.println("<table border='1'> <tr> <th>Inglish word</th> <th>Origin</th></tr>"); for(Map.Entry<String, String> word : inglishWords.entrySet()) { pw.printf("<tr> <td> %s </td> <td> %s </td> </tr>", word.getKey(), word.getValue()); } pw.println("</table> <p style='font-style:italic;font-size:small;float:right'>Results obtained at " + new Date() + "</p> </body> </html>"); }
  • 9. HTML Creation Example def writer = new StringWriter() def doc = new MarkupBuilder(writer) doc.html() { head { title("Words from Indian origin in English") } body { h1("Words from Indian origin in English") table(border:1) { tr { th("Inglish word") th("Origin") } inglishWords.each { word, root -> tr { td("$word") td("$root") } } } p(style:'font-style:italic;font-size:small;float:right', "Results obtained at ${new Date().dateTimeString}") } } def filename = 'index.groovy.html' new File(filename).write(writer.toString())
  • 10. Not Convinced?! Check XML Creation Example try (PrintWriter pw = new PrintWriter(new FileWriter("./words.xml"))) { pw.println("<inglishwords>"); for(Map.Entry<String, String> word : inglishWords.entrySet()) { pw.printf("t<language word='%s'> n tt <origin> '%s'</origin> n t </language> n", word.getKey(), word.getValue()); } pw.println("</inglishwords>"); } xmlbuilder = new groovy.xml.MarkupBuilder() xmlbuilder.inglishwords { words.each { key, value -> language(word:key) { origin(value) } } }
  • 11. Where to Learn More About Groovy?
  • 12. Some Dynamic Languages for .NET World