Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Streams, functional programming and Lambda expressions have opened up a whole new world of syntax for the Java language. The old forEach has new competition.

An example of a normal forEach of a list of objects was:

for (MyModel myModel : myModelList) {
    System.out.println(myModel);
}

This can be replaced with .forEach and the code gets much smaller.

myModelList.forEach(System.out::println);

One common thing to do with a forEach is to iterate over a set of data and pick and choose which objects should be added to another list.
An example of a forEach that filters a list is:

List<GameModel> externalGames = new LinkedList<>();
for (GameModel myModel : gameList) {
    if ("external".equals(myModel.getIdGameExternal())) {
        externalGames.add(myModel);
    }
}

This is when it gets fun. We can use .filter and .collect to transform this into the following. The .filter contains all of the logic that you would have had in an if statement. The .collect contains the processing necessary to convert the stream to a LinkedList.

externalGames = gameList.stream()
                        .filter(myModel -> "external".equals(myModel.getIdGameExternal()))
                        .collect(Collectors.toCollection(LinkedList::new));

Sometimes you need just one element from a list. Here is what a typical forEach loop looks like that filters a list down and then we get a reference to the first object in the list.

List<GameModel> externalGames = new LinkedList<>();
for (GameModel myModel : gameList) {
    if ("external".equals(myModel.getIdGameExternal())) {
        externalGames.add(myModel);
    }
}
gameModel1 = externalGames.get(0);

We can easily do the same thing using streams. In this case, I filter like before, then grab the first element. We pull out .findFirst to retrieve the first element of the stream, then use .get to make that object available.

gameModel1 = gameList.stream()
                     .filter(myModel -> "external".equals(myModel.getIdGameExternal()))
                     .findFirst()
                     .get();

Sometimes you have the case where you want to search through a collection of data and if an element contains a specific value, set something else. In this case, we use findFirst() and isPresent() to set a boolean value based upon an element in the collection having a specific value.

inBonus = bonusRedemptionModel.getBonusTransactions()
                              .stream()
                              .filter(b -> BonusOperationEnum.OPT_OUT.value().equals(b.getIdOperation()))
                              .findFirst()
                              .isPresent();

August 6th, 2015

Posted In: Collections, Java, java ninja, Javaninja

Tags: , , , , ,

Leave a Comment

I had a need to remove duplicates from a pre-existing Java List. I tried:

ids = new LinkedList<WatchedId>(new LinkedHashSet<WatchedId>(ids));

Seems easy enough, but the list kept returning no elements. I started clicking through the code and found the LinkedList constructor that takes a collection eventually calls

LinkedList.addAll(int size, Collection)

That method has the following line

Object[] a = c.toArray();

The implementation was in AbstractCollection.toArray(). I stepped through the code and I saw that the nodes were not being moved. Maybe that is a Mac JVM bug? I changed the type to an ArrayList and it worked. Maybe it has something to do with going from a double-linked backing object to a double-linked backing object.

ids = new ArrayList<WatchedId>(new LinkedHashSet<WatchedId>(ids));

September 27th, 2012

Posted In: Collections, Java

Tags: , , , , , , , ,

Leave a Comment

To parse a string into a DateTime object:

DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dt = fmt.parseDateTime(strInputDateTime);

To output the formatted value of a DateTime object as a String:

fmt.print(myDateTime)

January 11th, 2011

Posted In: Collections, Java, Joda-Time

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com