Steve On Java

Hacking Java, JavaFX, and Raspberry Pi
  • rss
  • Home
  • SvJugFX
  • 2014 Travel Map
    • 2013 Travel Map
    • 2012 Travel Map
    • Let’s Meetup!
  • Forms
    • Nighthacking Worldwide Beer Reimbursement
    • JFXtras Individual CLA
    • JFXtras Corporate CLA
  • Contact
  • NightHacking.com

20 “Cakes” of Java in Brazil

steveonjava | July 14, 2015

To celebrate 20 Years of Java we did a cross-country tour in Brazil for 20 days, visiting Java User Groups and Events across the country.  It was long and grueling, but a lot of fun.  And most importantly, we got to eat cake!  Cake for breakfast (thanks to Otavio and his chocolate passion) and a Java cake for dinner…  every single day!

We raced robots in Campinas

Untitled

And ate SOUJAVA cake!

Read the rest of this entry »

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Community, Events, Uncategorized
Comments rss Comments rss
Trackback Trackback

Java DevOps at the swampUP

steveonjava | May 7, 2015

The folks at JFrog definitely know how to put on events in style. For several years they have had an exclusive cruise at JavaOne for “Frogs and Friends”, and this year they stepped it up with a full day DevOps-focused conference in Napa, the heart of wine country.

The JFrog swampUP was definitely a meeting of the minds with a great cast of Java and DevOps Rock Stars milling around and chatting about state-of-the-art tooling in Java. Was great catching up with Carl Quinn of Java Posse fame and now at a very cool tech job with Riot Games. Guillaume Laforge was slightly jetlagged, but that didn’t stop him from ranting on the future of Groovy, which is now an Apache hosted project. And it was great to meet Seth Chisamore, the release engineering lead at Chef. I also happened to bump into Easy Bay JUG leader Chris Richardson and GR8Conf Organizer Søren Berg Glasius, so there was no shortage of expert hecklers to go around.

Here are some of the photos I took during the event:

The final keynote was given by Jagan Subramanian from Oracle who showed Artifactory running on big iron with some very impressive server setup.  The Oracle repository has grown to double-digit terabytes in size, which in itself is impressive.  However, the real story behind this is the network traffic, where they have done some clever hardware engineering tricks to keep things running smoothly all the way through the network switches in the data center.

I also presented an updated version of my “Confessions of an Agile Methodologist” talk that I got the JavaOne Rock Star award for. Believe it or not, in a previous life I was a DevOps/Agile guru, and a very early adopter of JFrog Artifactory. I am proud to say that they still have the best repository manager out there! :)

Confessions of a Former Agile Methodologist (JFrog Edition) from Stephen Chin
 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Agile
Comments rss Comments rss
Trackback Trackback

Java Lego Workshop 4 Kids

steveonjava | May 5, 2015

This past weekend I did a Lego workshop for the local Devoxx4Kids bay area chapter.  There were 35 excited kids from ages 8-14 who had their first taste of programming.  While they expected to simply play with Legos for a few hours, they ended up hacking their first Java code in Eclipse.

The kids did a great job, and all the groups were able to get some basic Java code working on the Lego Mindstorms EV3 platform.  They were using LeJOS, which is a great way to code for and deploy to the Lego intelligent brick using a robust programming language.  Here is a video of one of the completed projects (sorry for my shaky camera work):

Here are some of the photos from the event:

And finally the full slide show with build instructions, which can be downloaded from SlideShare:

Devoxx4Kids Lego Workshop from Stephen Chin
 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

More Java and VTS

steveonjava | May 4, 2015

I recently change roles at Oracle…  previously I was a Java Technology Evangelist and now I am a Java Community Manager.  So, you may be asking yourself what is the difference between an evangelist and a community manager…  Here is the quick breakdown:

  1. Evangelists preach while managers buy pizza…  looking forward to buying pizza for some JUGs!  :)
  2. They probably won’t “invite” me to customer meetings anymore…  somehow I am fine with that.
  3. The Java part is still the same, so I can legitimately get away with drinking gourmet coffee and calling it work!

And as part of my new role I am getting pulled into a lot of our community outreach efforts.  You will see more of these showing up on my blog, but the most imminent one is the upcoming Virtual Technology Summit (VTS).  It is like a conference, but without the annoying vendors.  ;)

Attendance at the VTS is free…  just register on one of these sites based on what region you are located in:

  • America – May 5th 9am to 12:30 PM PST
  • Europe – May 12th
  • Asia – May19th

I am particularly excited about Mark Heckler’s session.  He is going to talk about an autonomous land vehicle IoT navigator.  Based on the quality of his JavaOne talks, it will be an exciting presentation!

I hope to see you at one of the VTS events in the chat.

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
9 Comments »
Categories
Events
Comments rss Comments rss
Trackback Trackback

Congratulations to the 2014 JavaOne Rock Stars!

steveonjava | February 11, 2015

Duke Rocking OutJavaOne is well known for its:

  • Great Cuisine
  • Formal Dress Code
  • Excellent Content!

Each year we award the top speakers for the JavaOne conference with the prestigious JavaOne Rock Star Award. This is done by taking a look at attendee feedback, so it really represents the folks who created the best content and experience for the JavaOne audience.

Without further ado, here is the list of recipients for the JavaOne 2014 Rock Star Award:

  • Adam Bien
  • Aleks Shulman
  • Andrzej Grzesik
  • Anton Arhipov
  • Arun Gupta
  • Axel Fontaine
  • Baruch Sadogursky
  • Ben Evans
  • Brian Goetz
  • Brian Oliver
  • Cedric Champeau
  • Christine Flood
  • Fabian Lange
  • Frank Kim
  • Geertjan Wielenga
  • Greg Luck
  • Hadi Hariri
  • Hendrik Ebbers
  • Johannes Weigend
  • John Arthorne
  • John Brock
  • Josh Long
  • Kirk Pepperdine
  • Les Hazlewood
  • Linda DeMichiel
  • Mark Winterrowd
  • Martijn Verburg
  • Matthew McCullough
  • Maurice Naftalin
  • Michael Duigou
  • Michael Hill
  • Michael Hoffer
  • Mike McQuaid
  • Nikita Salnikov-Tarnovski
  • Paul Sandoz
  • Petr Jiricka
  • Rafael Winterhalter
  • Reza Rahman
  • Rich Hickey
  • Sander Mak
  • Simon Maple
  • Stephen Chin
  • Steven Pousty
  • Stuart Marks
  • Sven Peters
  • Tal Weiss
  • Trevor Lalish-Menagh
  • Trisha Gee
  • Venkat Subramaniam
  • Yoav Landman
Please join me in congratulating all of these excellent presenters! Oh, and just as a teaser, the JavaOne 2015 CFP should be opening next month, so stay tuned for that.
 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
3 Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

Oracle IoT Kids Workshop

steveonjava | August 7, 2014

So I just finished prepping 50 Raspberry Pi kits and 25 Lego sets for a kids programming workshop tomorrow, and put the finishing touches on the 99 page slide deck. Given the workshop doesn’t start for another 6 hours, I think that is pretty timely. ;)

I will post some pictures after the workshop, but here is the slide deck if you want to get a head start on the fun:

Oracle IoT Kids Workshop from Stephen Chin

The new Wind Turbine project is a lot of fun, and the directions are kid tested (Cassandra gave it a dry run and breezed through most of it without any help). Enjoy!

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

Top 3 reasons to register for JavaOne early…

steveonjava | April 25, 2014

JavaOne planning is already in full swing with the largest number of CFP proposals submitted in the past 4 years. However, you may not know, but we have made some changes this year that may make it worthwhile to sign-up a little earlier than usual.

1. Special Java 8 Pricing — If you signed up for the Java 8 Launch Stream, you should have received an e-mail with a special discount code for $200 off [note to self, don’t forget that the code is “DJS4″]. Combined with the super-saver discount available now (+$600 off), this is the lowest price for JavaOne — ever!

To use this you will have to hurry up, the code expires on May 2nd.

http://www.oracle.com/javaone/register/index.html

2. Invited Speakers — For the first time this year we have invited a small set of Rock Star speakers to come back to give presentations at JavaOne. Together with our first round picks, this gives you 18 ways to convince your boss to let you come to JavaOne:

  • 11_speakerdavid_blevinsTrisha_GeeAdam Bien
  • Anatole Tresch
  • Arun Gupta
  • Ben Christensen
  • David Blevins
  • David Svoboda
  • Hendrik Ebbers
  • James Ray
  • artworks-000067309626-ur19q7-t500x500thoughtworks_1Jim Manico
  • Les Hazlewood
  • Michael Hoffer
  • Niklas Therning
  • Dr. Rebecca Parsons
  • Patrycja Wegrzynowicz
  • Toni Epple
  • Trisha Gee
  • Simon Elliston Bal
  • Woody Zuill
  • Yara/Vinicius Senger

3. Beat OpenWorld to the Hotels — By signing up early, you have a window of opportunity to grab up some of the best hotels in San Francisco before the availability drops and the rates climb. Time to treat yourself and stay in the Hilton or Parc right upstairs from the big event. ;)

Oh, and some specific advice for folks I know love to wait…

3S. For all you prospective speakers out there, I confirmed that you get a full refund once your talk is accepted. So get your discounted ticket and reserve your hotel now!

3J. And for the JUG members who have used the discount code in past years… feel free to sign-up using the Java 8 pricing knowing that you are getting the lowest possible price.

We have a lot of new, exciting stuff in the works, so I hope to see you at JavaOne!!!

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

NightHacking Tour – 1st Half Highlights

steveonjava | April 6, 2014

NightHacking-Java-8-Tour---BadgeIn case you have missed the first half of my insane tour through Europe, I have stayed in more cities in the past month than most people visit in a decade. Staring in Munich, I rented a motorcycle, loaded up a few hundred pounds of video and demo equipment, and have been riding around Europe to celebrate the launch of the Java 8 release with an itinerary including 4 conferences and 30 JUGs!

So far there have been over 30K views from Java developers of the videos, so thanks everyone for supporting the tour!  Here are some of the highlights:

Unexpected guests in Munich

I kicked off the tour with a bang in Munich, joining an event on DukeScript with Toni Epple, and we had two surprise guests. Marcus Eisele, Oracle ACE, Java Champion, and conference chair for JavaLand showed up for a surprise visit. Also, Kirk Pepperdine, Java Champion and performance testing guru, flew in from Hungary just for the event!  You can watch the action at the start of the NightHacking Tour in Munich here:

Geek Winery

After a great event in Brno (kudos to the team there on building the largest Czech JUG from the ground up in the past 2 years), Professor Petr Adámek invited me over to stay at his wine cellar and I couldn’t refuse. The wine cellar is excavated out of compacted sand that is now as hard as rock, but provides fertile soil for their Cabernet Blanc grapes. It also is a breeding ground for some “good” molds that have grown over an inch thick in some places and give the whole cellar a very distinct aroma. The cellars pre-date WWII, and as such have a long history including having their entrances demolished by soldiers to prevent refugees from hiding. However, they were able to recover the cellars and re-excavate them to recover the wine-making business. The 2004 Cabernet Blank shown here was a masterpiece (including a heavy plume of mold for character)… so what were you doing in 2004? [Hopefully the answer is playing with Generics right after they cane out in Java 5]
  

Wind, Sleet, and Hail in Poland

The fix for a hangover? Some hail stones raining down on your motorcycle! I think my most adventurous (read life-threatening) journey so far has been the leg from Brno to Krakow. It started out as a very windy day with my 600 pound machine getting kicked around by 40mph winds and trucks passing by on narrow roads. A little on and off drizzle, so I put on NAO’s raincoat and continued pressing on for the 6 hour trek up to Krakow. Little did I know that I was headed straight for a storm front, which started with some nice hail stones and went into a full-blown snowstorm with sleet covering my windshield. Fortunately the road was warm enough that the snow melted immediately and there was no ice forming on the bridges yet. Needless to say, I was a bit frazzled by the time I made it to Krakow, but arrived in time and put on a good show (the JUG members in Poland are super-geeky — just drop by GeeCON and you will know what I mean!)

Does JavaFX Run on That?

I spent the weekend in Munster at Gerrit Grunwald’s place and we did some *real* NightHacking. First we did a toy show with the JUG Munster guys including Michael Hoffer who brought some cool things he had been 3D printing using a JavaFX-based geometry designer. Then the real NightHacking started as Gerrit and I started playing around with a few new devices. He helped me get a version of his QlockTwo application deployed to my Android watch, which was surprisingly easy to do. Next we spent some time getting the Udoo to work with Java 8 and JavaFX. Initial support was as easy as copying over the Java 8 SDK and running JavaFX in GTK mode. The performance was surprisingly good, beating the Raspberry Pi by several orders of magnitude (although this should be no surprise with a quad-core imx.6 processor at your disposal). Although like any good hack, the devil was in the details — getting the chalk-elec 7″ touchscreen to run at 1 to 1 pixel resolution required booting into the special pre-loader and typing multi-line commands over a primitive terminal. (this is clearly an area the RaspberryPi shines)

The real Java 8 Launch Stream

If you were one of the thousands of folks watching the launch stream on the 25th, I am sorry to tell you, but you missed out on the real action. At JavaLand we had a live panel on stage commenting on the launch video in the background with some of the most knowledgeable people in the community discussing Java 8 over 1… 2… 3… er, a lot of beers! Fortunately, this was both broadcast (kudos to the JavaLand team on the great network and stage setup!) and also recorded, so you can watch the action at the most exciting new conference in Europe!:

NAO Hacking by the Lake

JUG Bodensee is a new Java user group started this year by NetBeans Dream Team member Sven Reimers, and a regular participant in the NightHacking Worldwide events. Our second NightHacking Worldwide event was a NAO lab with Aldebaran Robotics, programming the 2 foot tall humanoid robot to do all sorts of crazy things. JUG Bodensee successfully got a few programs to run remotely, but was having challenges getting more complex examples to run without a robot to test. Well, there was no way I could miss the chance to drop by in person with my NAO robot, and they created some really awesome programs in the span of just a few hours!

Lego Duke had a great fall…

The Geneva JUG had a record turnout for the evening NightHacking event [~150 attendees], which was held in an awesome venue with a real hardwood stage. Duke made an impression on stage when the planted audience volunteer “accidentally” lost their grip on Duke and he literally fell to pieces on stage, transforming into “Robo Duke”! Even with his lego skin in tatters, Duke was still able to (mostly) balance and the Geneva JUG got a unique view into the internals of our favorite Java mascot. Here is an outtake of Duke’s little fall:

I am writing this from 25,000 feet up in the air. Would rather be on the autobahn cruising at 200kph, but this was the fastest way to get home for a quick 48 hour stopover to visit the relatives in San Francisco [my wife and 2 girls]. Also a great opportunity to do a quick resupply [more stickers!] and give Lego Duke a relaxing visit to the glue spa.

Quick resupply run to SF before my #NightHacking Tour continues. Lego Duke is undergoing surgery… pic.twitter.com/3MX7viwu94

— Stephen Chin (@steveonjava) April 6, 2014

On Monday I will be back in Marseille for some more NightHacking, and am continuing the tour through France, Spain, Portugal, and speaking at Devoxx France before I switch continents to India. I hope to see you on the 2nd half of the Java 8 NightHacking Tour!

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
1 Comment »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

Java 8 Released! — Lambdas Tutorial

steveonjava | March 18, 2014

To celebrate the release of Java 8 which was released just minutes ago, I am publishing a draft version of my Java 8 Lambdas Tutorial.  It is a nice visual way to learn the Streams API, and will help you get started taking advantage of lambdas in your own applications from day 1.  This article is scheduled to appear in the next Java Magazine release, so please look forward to the final version, and I will do my best to incorporate comments and feedback if they meet the publication deadline.

pic1Mary Had a Little Lambda

Java lambdas are the most impactful feature to enter the Java language since the release of generics in Java 5.  It fundamentally changes the programming model, allowing a functional style of development, and supports efficient parallelization of code to take advantage of multi-core systems.  Although as a Java developer you will first notice the productivity improvements that you gain using the new lambda-enabled APIs in Java 8.

In this article we will walk you through the new Streams API for working with collections and data by using a retro game written in JavaFX.  This game is both a simple Java 8 application written from the ground up to showcase lambdas best practices, and also a visual guide to programming with the Streams API.  However, we will first lay the foundation with an introduction to the lambdas language changes.

Introduction to Lambdas

To use lambdas you must be using a recent Java SDK (8 or higher) and set the language level to Java 8 when you compile.  You can download the latest Java SDK version from:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Developing lambdas is a lot easier when using an IDE that supports the new syntax.  Most Java IDEs have been updated with lambdas support and will assist you with real-time error reporting and code completion of lambdas.  NetBeans and IntelliJ are noteworthy as having the best lambdas support out of the box at the time of the Java 8 release, and both work well with the example we are demonstrating here.

To demonstrate how the new lambdas feature works, here is a short snippet of code that iterates through a list of shapes and changes the blue ones to red:

for (Shape s : shapes) {
  if (s.getColor() == BLUE)
    s.setColor(RED);
}

In Java 8 you could rewrite the same code by using a forEach and a lambda expression as follows:

shapes.forEach(s -> {
   if (s.getColor() == BLUE)
     s.setColor(RED);
});

The lambda form makes use of a new method on the Collection interface called forEach, which takes a lambda expression and evaluates it for all the contained elements.  Similar API enhancements have been made throughout the Java core classes in order to simplify the usage of lambda expressions.

A related question you may have is how the Java team is able to add in new methods to interfaces without breaking backwards compatibility.  For example, if you have code that implements the Collection interface and does not have a forEach method defined, then won’t the upgrade to Java 8 break your implementation?  Fortunately, another feature called extension methods solves this problem in Java 8.  The implementation of forEach on the Collection interface is shown in the following code listing:

interface Collection<T> {
  default void forEach(Block<T> action) {
    Objects.requireNonNull(action);
    for (T t : this)
      action.apply(t);
  }
  // Rest of Collection methods…
}

Notice the new default keyword, which indicates that the method will be followed by a default implementation.  Subclasses are free to create their own implementation of the method, but if there is none defined they will get the same standard behavior as defined in the interface. This allows new methods to be added to existing interfaces in the core Java classes, as well as in your own libraries and projects.

The actual lambda syntax is quite simple…  in its full form you supply the types and parameters on the left, put a dash, greater-than sign [->] in the middle, and follow that with a method body in curly braces:

(int a, int b) -> { return a + b; }

In the case where the function returns a value, this can be simplified by removing the curly braces, return keyword, and semicolon:

(a, b) -> a + b

Furthermore, in the case where there is only one parameter you can leave off the parenthesis:

a -> a * a

And finally, if you have no parameters, you can simply leave the parenthesis blank, which is common for replacing Runnable implementations or other no-parameter methods:

() -> { System.out.println("done"); }

In addition to the basic syntax, there is also a special shortcut syntax called “Method References,” which lets you quickly create lambda expressions that refer to a single method as the implementation.  The following table summarizes the different types of method references along with the equivalent long form lambda syntax.

Method Reference Lambda Equivalent
Objects::toString obj -> Objects.toString(obj) Static method reference
Object::toString obj -> obj.toString() Member method reference
obj::toString () -> obj.toString() Object method reference
Object::new () -> new Object() Constructor method reference

The last concept that is important when working with the new lambdas methods is the creation of interfaces that allow you to accept lambda expressions. For this purpose, any interface that has one explicitly declared abstract method can be used to accept a lambda expression, and is thus called a functional interface.

As a convenience, they introduced a new FunctionalInterface annotation that optionally be used to mark interfaces in order to get assistance from the complier in checking to make sure your interface meets the single explicitly declared abstract method requirement:

@FunctionalInterface
interface Sum {
  int add(int a, int b);
}

This is a recommended best practice, because it will catch corner cases in the definition of functional interfaces, such as the inclusion of default methods that allow you to have multiple methods defined on a functional interface since they are not abstract and don’t count towards the single abstract method requirement.

Now that you have a basic understanding of the lambda syntax, it is time to explore the streams API and show the power of lambdas in the context of a visual example.

Retro Gaming with Lambdas

Mary had a little lambda

Whose fleece was white as snow

And everywhere that Mary went

Lambda was sure to go!

pic2Nowadays video games are all about high-resolution 3D graphics, cinematic quality cut scenes, and difficulty levels that range from newbie to pacifist.  However, in the good old days of gaming we just had sprites…  cute, pixelated little figures dancing and RPG-walking their way through well-designed and insanely difficult levels.

Sprite-based graphics also happen to be really simple to program, allowing us to build a full animation system in under 400 lines of code.  The full application code is in GitHub at the following location:

https://github.com/steveonjava/MaryHadALittleLambda

For all the graphics used in the game, the images are laid out in a standard 3×4 tiled format as shown in the adjacent sprite sheet for Mary. The code for animating sprites is done (of course) using a lambda, and simply moves the viewport around a tiled image in order to produce a 3-frame walking animation [horizontal] and to change the direction the character is facing [vertical].

ChangeListener<Object> updateImage =
  (ov, o, o2) -> imageView.setViewport(
    new Rectangle2D(frame.get() * spriteWidth,
                    direction.get().getOffset() * spriteHeight,
                    spriteWidth, spriteHeight));
direction.addListener(updateImage);
frame.addListener(updateImage);

Add a static image for a background, and some key event listeners to move the character on input, and you have the basics of a classic RPG game!

pic3

Generating Streams

There are several ways to create a new Java 8 Stream.  The easiest way is to start with a collection of your choice and simply call the stream() or parallelStream() methods to get back a Stream object such as in the following code snippet:

anyCollection.stream();

You can also return a stream from a known set of objects by using the static helper methods on the Stream class.  For example, to get back a stream that contains a set of Strings, you could use the following code:

Stream.of("bananas", "oranges", "apples");

Similarly, you can use the Stream numeric subclasses, such as IntStream, to get back a generated series of numbers:

IntStream.range(0, 50)

But the most interesting way to generate a new series is to use the generate and iterate methods on the Stream class.  These let you create a new stream of objects using a lambda that gets called to return a new object.  The iterate method is particularly interesting, because it will pass in the previously created object to the lambda.  This lets you return a distinct object for each call, such as returning all the colors in the rainbow iteratively:

Stream.iterate(Color.RED,
  c -> Color.hsb(c.getHue() + .1, c.getSaturation(),
                                  c.getBrightness()));

To demonstrate how this works visually, we are going to add in a new element to the application that generates sheep when we step on it.

The code for the new Barn class is as follows:

public static class Barn extends MapObject {
    static final Image BARN = loadImage("images/barn.png");
    public Barn(Main.Location loc) {
        super(BARN, loc);
    }
    @Override
    public void visit(Shepherd s) {
        SpriteView tail = s.getAnimals().isEmpty() ?
            s : s.getAnimals().get(s.getAnimals().size() - 1);

        Stream.iterate(tail, SpriteView.Lamb::new)
            .skip(1).limit(7)
            .forEach(s.getAnimals()::add);
    }
}

This code specifies the image to use for the sprite-based graphics, which is passed in to the super constructor, and implements a visit method that has the logic that will get executed when Mary steps on the Barn.

The first statement in the visit method simply gets the last element from the list of animals following Mary, or returns her if there are no animals yet.  This is then used as the seed to the iterate method, which gets passed to the Lamb constructor for the first invocation of the lambda.  The lamb that gets generated by this is then passed in to the Lamb constructor for the second invocation, and this repeats in succession.

The resulting stream includes the seed, so we can use the skip function to remove that from the stream, and it is theoretically infinite.  Since streams are lazy, we don’t need to worry about objects getting created until we add a terminal operation, but an easy way to fix the length of the stream is to use the limit function, which we will give a parameter of 7 to generate seven sheep following Mary.  The last step is to add a terminal operation that will use the stream.  In this case, we will use a forEach function with the lambda expression set to a method reference to the add method on the list of animals.  The result of executing this lambda is the addition of sevens lambs following Mary in succession:

pic4

The next element we are going to add to the game is a rainbow that will demonstrate filtering in the Streams API.  The way the filter function works is that it takes a predicate lambda, which evaluates to true or false for each element in the stream.  The resulting stream contains all of the elements where the predicate lambda evaluated to true.

For the logic of the rainbow, we will execute a filter that returns every 4th animal in the stream and apply a JavaFX ColorAdjust function to shift the hue to match the passed in color.  For white we are using null (no color shift).  The following code is the implementation of the visit method for the rainbow MapObject:

s.getAnimals().stream()
    .filter(a -> a.getNumber() % 4 == 1)
    .forEach(a -> a.setColor(null));
s.getAnimals().stream()
    .filter(a -> a.getNumber() % 4 == 2)
    .forEach(a -> a.setColor(Color.YELLOW));
s.getAnimals().stream()
    .filter(a -> a.getNumber() % 4 == 3)
    .forEach(a -> a.setColor(Color.CYAN));
s.getAnimals().stream()
    .filter(a -> a.getNumber() % 4 == 0)
    .forEach(a -> a.setColor(Color.GREEN));

And when Mary steps on the rainbow, all the lambs get colored according the Color values you specified:

pic5

“Lamb”da Question 1: What happens if you step on the barn after visiting the rainbow?

Another way to use filtering is to take advantage of the new methods added to the Collection API that accept a predicate lambda.  These include removeIf which filters out all the elements that don’t match the given predicate, and filtered, which is on ObservableList and returns back a FilteredList containing only the items that match the predicate.

We will use these to implement a Church object that will filter on “pure” animals.  Any animals that are white in color will be cooked by the church staff to feed the needy.  This includes incrementing the counter of “Meals Served” on the sign and removing the “pure” animals from the list.  The code for the church visit method is shown below.

Predicate<SpriteView> pure =
    a -> a.getColor() == null;

mealsServed.set(mealsServed.get() +
    s.getAnimals().filtered(pure).size()
);

s.getAnimals().removeIf(pure);

And you can see the result of successively stepping on the rainbow and church in the following screen capture.

pic6

“Lamb”da Question 2: Is it possible to use the church to clear all the animals after they have already been colored?

Probably the most powerful operation in the Streams API is the map function.  This allows you to convert all the elements in the stream from one type of object to another, performing powerful transformations along the way.  We will use this to implement a chicken coop where all the animals following Mary will get converted into eggs.

I have two implementations of the visit method for the chicken coop.  The first one uses a single map operation with a lambda expression to replace the stream elements with eggs as shown here:

// single map:
s.getAnimals().setAll(s.getAnimals()
    .stream()
    .map(sv -> new Eggs(sv.getFollowing())
).collect(Collectors.toList()));

The second implementation uses method references with a chained set of map operations to first convert the stream to a stream of whom the animals are following, and then to call a constructor method reference to create the eggs, passing in the following information to the constructor parameter:

// or a double map:
s.getAnimals().setAll(s.getAnimals()
    .stream().parallel()
    .map(SpriteView::getFollowing)
    .map(Eggs::new)
    .collect(Collectors.toList())
);

Both of these code fragments behave and perform similarly since the stream API is designed to be lazy and only evaluate the stream when a terminal operation (such as collect) is called.  So it is primarily a style issue for which one you prefer to use.  Running the program with the new chicken coop MapObject will let you generate eggs from lambs as shown in the following picture:

pic7

“Lamb”da Question 3: If you send colored lambs to the chicken coop, what color are the eggs?

Notice that each of the eggs sprites contain three little bouncing eggs.  Wouldn’t it be nice if we could hatch these guys into chickens?

To hatch the eggs we will add in a new MapObject for a nest where the eggs will be hatched into a group of three chickens using the following hatch method:

public static Stream<SpriteView> hatch(SpriteView sv) {
    if (!(sv instanceof Eggs)) {
        return Stream.of(sv);
    }
    return Stream.iterate(sv, Chicken::new).skip(1).limit(3);
}

Notice that this method returns back a Stream of objects, which means if we used a normal map operation we would get back a Stream of Streams.  In order to flatten the Stream into a single list of chickens, we can instead use flatMap, which will both map the stream using a lambda function and also collapses the nested Streams into single list of objects.  The implementation of the nest visit function utilizing flatMap is shown below:

s.getAnimals().setAll(s.getAnimals()
    .stream().parallel()
    .flatMap(SpriteView.Eggs::hatch)
    .collect(Collectors.toList())
);

Now, upon bringing eggs to the nest, you will get an explosion of chickens as shown in the following screenshot:

pic8

“Lamb”da Question 4: Approximately how many animals can you add before the game runs out of memory?

The final element we will add is a fox to demonstrate how to reduce a stream.  For this, we will first map the stream to a list of integers according to the scale of the animals, and then we will reduce that using a sum method reference into a single value.  The reduce function takes a seed value (which we will use 0 for), and a function that can reduce two elements into a single result.  This lambda will be applied recursively for all the elements in the stream until a single value results, which will be the sum of all the animal scales.

Double mealSize = shepherd.getAnimals()
    .stream()
    .map(SpriteView::getScaleX)
    .reduce(0.0, Double::sum);

setScaleX(getScaleX() + mealSize * .2);
setScaleY(getScaleY() + mealSize * .2);
shepherd.getAnimals().clear();

We then take the sum (stored into the variable called mealSize) and use that to stretch the fox proportionally.  You can see the result of a very tasty meal for the fox in the following picture:

pic9

“Lamb”da Question 5: How can you change the code for the Fox to make him fatter when he eats?

In this article we covered the basic lambda syntax, including method references, extension methods, and functional interfaces.  Then we went into detail in the Streams API, showcasing some of the common operations such as iterate, filter, map, flatMap, and reduce.  As you have seen, Java 8 lambdas dramatically shifts the programming model, allowing you to write simpler and more elegant code, and opening up the possibility of new powerful APIs like Streams.  Now it is time to start taking advantage of these capabilities in your own development.

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
2 Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

Devoxx4Kids Raspberry Pi and NAO Workshop

steveonjava | February 19, 2014

With the help of some local parents, I ran a Raspberry Pi and NAO Robot workshop for teach programming to 10-14 year old children. By the end of the 4 hour session, all of the kids were able to assemble a Raspberry Pi and touchscreen, program changes to a simple Java-based game, and create behaviors that ran on the NAO humanoid robot. Not bad for a sleepy vacation day. :)

We were fortunate enough to the team from Aldebaran Robotics who flew in all the way from France to help out. Also, the kids were great, exceeding my expectations, and even impressing the Aldebaran guys.

Here are some photos from the event:

The updated slide deck for teaching Java on the Raspberry Pi is here:

And the English translated version of the NAO robotics programming workshop is here:

(Credit to Daniel De Luca for content creation and Nicolas Rigaud on translation)

Special thanks to Nina Shulman for all her hard work coordinating the workshop!

 

Share this:

  • Twitter
  • Facebook
  • Google
Comments
No Comments »
Categories
Events, JavaFX, Kids, Presentation
Comments rss Comments rss
Trackback Trackback

« Previous Entries

Follow @steveonjava Follow @_nighthacking
Travel Map

Publications

  

Affiliations

Awards

2009/2011/2012 JavaOne Rock Star!

Disclaimer

Views and opinions expressed here are all my fault... complain to me, not my employer. :)
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox