java 8 lambdas from the nyc java meetup

I really liked the Java 8 Lambda talk from yesterday evening’s meetup so I’m blogging about it.  I like lambdas for the same reasons I like regular expressions – so much power and clarity!   The speaker was Timothy Fagan from Lab 49.  Photos of most of the slides are on the meetup website.  (not sure if you have to be a member of the meetup to view the pictures.)  Ok, here’s what I learned.  There are many blog posts on lambdas better than mine like the “Everything about Java 8” one.  I’m blogging anyway to solidify my understanding.

Where development is up to

  • Feature complete now.
  • General Availability March 2014.
  • Oracle delayed Java 8 date so lambdas would be included

Where we came from

  • Java has always had functors (objects that are classes)
  • Java 1.0 – could create classes to be functors – for example Runnable interface with run method
  • Java 1.1 invented anonymous inner classes  – complexity, performance issues (megamorphic call size or stack?)
Syntax
General case:
  • (paramList) -> expression | { statements}

Special case for single parameter: (Can leave out parens if one param. Need parens if zero params)

  • param -> expr | { stmt }
The return type is expr or return type of stmt.  stmt can return void if no return value
Examples
Uses signatures and return type to match new thread sig. This conforms to Runnable interface – returns void
  • new Thread(() -> System.out.println(“foo”))
Uses type inference to determine types of a and b
  • words.sort ((a,b) -> a.length() – b.length())

Only invokes lambada expression if logger set to right level.  This is a new interface that returns String

  • Logger.finest (()-> f.toString())
Only does expensive call if key not already in map:
  • map.computeIfAbsent(1234444, number-> getObjectFromDB())
Cast tells Java they are strings.  Interesting:  First time in Java you can have an object that will require a cast in order to compile when assigned to object.  May need to cast if ambiguous which constructor it uses

  •  Comparator c = (Comparator<String>) (a,b) -> a.length() – b.length().
General
  • Oracle combed thru java api looking for opportunities to use lambada expressions
  • Currently error messages are confusing. Builds on wildcard confusing messages
  • Can use lambda epressions in code you write if interface with a single method
  • A lambda is like a method that you dont know the name of on the class you are coding
    Foo..lambda$0 – class and method
    foo$$Lambda$1.methodYouCalled – link from your class to lambda – synthetic method – can’t view source
  • @Functional – requires interface has only one interface so can use as lambd
  • Can build own currying. Need to read about it – went over my head
  • Intellij idea community edition already supports lambdas
  • Jdk8.java.net has javadoc
 Scope
  • Lambdas are scoped in “this” scope not an anonymous inner class
  • System.out.println(this) prints current method name. Gives error if try in static method
  • Can refer to local var of param without having to use final keyword unlike anonymous inner classes  Still needs to be effectively final. Cant reassign after lambda expression. Compiler will catch you if you try to assign it.
  • Local vars are “caputred” which requires a new lambda to be created each time. Noncapturing lambda expressions will reuse instances. If not capturing, don’t need to worry about heap/garbage collector.
  • “this” refers to the point of creation of the lambda expression.  Not necessarily the current class (if passed around). Has some characteristics of a closure, but not all characteristics of closures
Limitations
  • Cannot break or continue outside of lamdba expression but can do so within block of statements in lambda
  • Cannot access non effectively final variables
  • Cannot implement abstract classes even single abstract method (SAM) abstract classes. Must use interfaces.
  • Exceptions in a lambda handled as per anonymous inner classes . A pain if functional interface does not throw exception. Would need a try catch to convert it.
Method References
These are all equivalent:
  • names.forEach(s -> sop)
  • names. ForEach(System.out::println) – uses method references – this is println on a specific object (system.out)
  • Static final Consumer PRNT =  System.out::println; names.forEach(PRINT)
Consumer has apply method of type T. So it can infer to pass forEach param to println. Can be more complex. Can have Printstream::println in which case must pass object to call println on as well.
Chaining with Streams
Stream.of(a,b,c).peek(a->sop)anyMatch(a->a.equals(r))
  • Peek doesn’t alter state. Can insert any where in chain to debug what is going on in stream
  • AnyMatch checks if any are true.    (The presenter wasn’t sure off the top of his head if it is a short circuit operator.  I just checked; it is)
  • AnyMatch lambda must create each time called because r is a variable so caputring. Peek lambda only created once. Don’t know if performance hit enough to worry about but suspect not. And even if a problem now just in time compiler will probably optimize it by ship date
Stream is a one time provider of values. May create lazily on demand. Permits for infinite streams – don’t try to count on one of those!  Examples:
  • Arrays.stream()
  • BufferedReader.lines()
  • IntStrem.range(0,100)
  • IntStream.ints().limit(100)
  • Random.ints() – infinite stream
  • ZipFile.stream()
Methods on Stream
Intermediate – defers execution.  Does not execute until need to.  That way can optimize if don’t need all values
  • Map , reduce, flatmap, mapTo
  • Filter, substream, limit, sorted, distinct (substream means skip first x)
  • Peek, parallel
Terminal – must be at end of chain
  • ForEach, count, min, max, sum (only on numeric streams)
  • AllMatch, anyMatch, noneMatch
  • FindFirst, findAny
  • Collect – collect data from stream and return something that isn’T a stream such as map of lists, min, collection or join strings with delimiter
java.util.function package
  • Function<T,R>  t input, r output
  • Predicate <T> – t input, boolean output
  • Consumer <T> a t input no output
  • Supplier <T> – no input, t output
  • BinaryOperator<T> – take two T’s an inout and returns one as output
and many more
Options
  • Optional<Long> o -returns an object that may or may not hold a long
  • o.get() to actually get the long
  • Throws exception if no value
  • o.ifPresent to check if there
  • o.orElse(a) – returns from get or hard coded value if not
Use carefully
New patterns
  • Try to pass streams around   Don’t need to keep converting to list.  Limitations on streams are not being able to go backwards and forwards and that can’t serialize.
  • Can now put static methos on interface
    comparator.comparing(lambda). ThenComparing(Comaprator.naturalOrder())

Multi core

B -> b.parallel().count() – can take advantage of multiple cores – can chop up work – uses work stealing – breaks up into smaller pieces so caget work from busy neighbors

coursera signature track

One of the difficulties with online courses is how they offer credentialing.  Many classes offer a certificate.  Unfortunately, it isn’t worth the bytes it is stored in as anyone could have taken the class for you.  (Students: it is still fine to use it as a conversation piece.)  There are a few ways to deal with this:

  1. The honor system – I got my Masters degree at Regis University.  Most exams and projects were the honor system.  The only thing that wasn’t was the thesis presentation.  And that was a phone call so someone else could have done it for me.
  2. Testing at Prometric/Pearson.  Another moderator at CodeRanch got her Bachelors degree at Western Governors University where much of the course work is a series of certifications.
  3. Proctored exams at work/school/the library – When I was researching online Masters degrees, many schools had you take their exams proctored by someone local.  I didn’t go this route because I didn’t want to keep bothering people by asking them to proctor.  And in New York City, the librarians are busy with their actual job responsibilities and aren’t going to proctor an exam.

Coursera and Udacity have been using the honor system to date.  Udacity is starting a $7000 masters degree.  Coursera is starting a signature track.

Why I tried the signature track

Mostly curiosity.  Also it said that the professor gets a small portion of the fee.  And the professor (@drchuck) was by far the most engaged I’ve ever seen in an online class.  Perhaps a bit too engaged!  He’s on twitter what feels like constantly, posts in the forums and does physical office hours as he travels around the world.

How much does it cost

Coursera says it costs between $30 and $100 per class.  I think I paid $39.

How does it work

When signing up, you take a webcam photo of yourself and one of your drivers license (or other id.)  You also type a sentence about not cheating.  Then after each assignment, you re-type that sentence and re-take your photo.  Your typing pattern is compared to verify it is you.  In theory, your photo is checked as well.  I say in theory because a student said he put up a picture of his dog and nothing happened.

Was it worth it

Only in that I was curious.  I wouldn’t do it again.  It was annoying to have to keep typing the sentence and taking a photo.  I don’t need a certificate for anything.  And it STILL doesn’t prove you didn’t cheat.  Just that you were present when the assignments were submitted and quizzes were taken.

The interesting thing is that the course was definitely worth $39.  It was a fun review of internet history and some things I never knew.  But paying for the benefit of a somewhat verified certificate isn’t.

 

using an over the air antenna for the time warner cbs blackout

I am a Time Warner TV customer because they have a monopoly.  I don’t know if FIOS is any better, but it is a moot point at the moment.  (And yes Scott, I know there are options like Tivo but you still need cable underneath it to get to the shows.)  tv-antenna

Currently in New York and a few other cities, CBS is blacked out on Time Warner because of a dispute.  I wasn’t worried when I heard it because I *maybe* watch CBS once a week during the summer and I  have an over the  air antenna.  However, starting August 25th (US Open Preview show date), I watch CBS a lot.  I decide to take this weekend as an opportunity to take my antenna out of a bag and make sure it still works.  (Which it should because it did in September when I bought a new TV.)  And to make it make it so I don’t need to keep unplugging wires to switch between cable and over the air.  I expect CBS and Time Warner to reconcile before the US Open.  But I also want to be prepared so I’m not scrambling.

What about Aereo?

An alternative to a physical antenna is Aereo but I’ve heard it isn’t easy to set up while using Time Warner.  It’s also $8 month after the trial ends.  Which is fine if you are replacing cable but isn’t the best temporary addition.  As of April, Aereo was deemed legal.  Last month an exec at TIme Warner said “if [Aereo] is found legal, we could conceivably use similar technology.   Which means even without another legal challenge, it may become better integrated into cable.  Maybe a little antenna in the cable box?  [Personally, I’ve always found it silly that cable companies had to pay for something that is free over the air.]

If you need to buy an antenna

I’ve had my antenna for about 8 years.  The exact model probably isn’t made anymore, but it is made by Terc and looks like this one.

If I needed to buy an antenna now, I’d go with this one.  It is omni directional which means you don’t have to fiddle with the “rabbit ears” to get reception and it takes up less room.  And it has optional amplification.  Amplification is supposed to make it easier to pick up a weak signal.  In practice, it didn’t help when I tried it in San Diego.  (I suspect in cities this is less important.)  But I’d definitely go with an omni over rabbit ears.

If you need to buy an antenna, they are sold at Best Buy or online.  It’s possible there has been a run on antennas because of the Time Warner/CBS issue though.  In which case online might be more helpful.

Optional hardware
tv-ab

If you are using an antenna for just one station, you’ll be switching back and forth between over the air and cable.  I recommend getting an A/B switch.  They aren’t inexpensive and can be found at your local hardware store.  You’ll also need an extra wire (coaxial cable) to connect the switch to the tv.  I had these parts in my “electronics drawer” so I took it out.

Prep

  1. Look for your TV remote.
  2. Check to see where the over the air stations broadcast from.  (If you live in NY, you can skip this step.  They all broadcast from Manhattan.)
  3. Pick a spot for your antenna.  In general, near the window is good.  If you have rabbit ears, also try to point one ear in the direction the over the air stations are broadcasting from.

Trying it out – without an A/B switch

Initial Setup:

  1. On the back of the TV is a plug called “ant in.”  Unplug this wire.  If you can’t find it, look for the round wire that goes from your cable box to the TV.  
  2. Plug your antenna wire into “ant in”.
  3. On your TV, set it to use “air” instead of “cable.”  You can actually leave it like this.  The cable is smart enough to get through when it is plugged in even if you are set to “air.”
  4. On your TV, run “auto program”.  This scans the over the air channels for ones it can find.
  5. Choose channel list or flip through the channels to find the one you want.  Depending on your TV, you may be able to type the “old analog” channel number.  For example, in NY this is channel 2 for CBS.  You may need to know the new digital channel though.  In NY this is channel 43 for CBS.

Switching back to cable:

  1. Unplug the antenna from “ant in”
  2. Replug the cable wire to “ant in”
  3. Select channel 3 on your tv
  4. Proceed normally for cable.

Switching back to over the air tv:

  1. Unplug the cable wire to “ant in”
  2. Replug the antenna from “ant in”
  3. Select channel you wish to watch on your tv

Trying it out – with an A/B switch

Initial Setup:

  1. On the back of the TV is a plug called “ant in.”  Unplug this wire.  If you can’t find it, look for the round wire that goes from your cable box to the TV.
  2. Plug the A/B switch into “ant in”
  3. Plug your antenna wire into the A/B switch.
  4. Plug your cable wire into the A/B switch.
  5. On your TV, set it to use “air” instead of “cable.”  You can actually leave it like this.  The cable is smart enough to get through when it is plugged in even if you are set to “air.”
  6. On your TV, run “auto program”.  This scans the over the air channels for ones it can find.
  7. Choose channel list or flip through the channels to find the one you want.  Depending on your TV, you may be able to type the “old analog” channel number.  For example, in NY this is channel 2 for CBS.  You may need to know the new digital channel though.  In NY this is channel 43 for CBS.

Switching back to cable:

  1. Flip the the switch on the A/B to point to cable
  2. Select channel 3 on your tv
  3. Proceed normally for cable.

Switching back to over the air tv:

  1. Flip the the switch on the A/B to point to antenna
  2. Select channel you wish to watch on your tv

Summing it up

The choice of whether to use an A/B switch largely depends on whether you already own one and how hard it is to get to the back of your TV.  If you can get to the back of the TV easily and aren’t switching every day, it isn’t really worth getting the switch.  But I had it, so no harm in taking it out.