For those who are disappointed for the lack of lambda expressions and some other functional features in Java

Today I just found a cool java library which made me really happy. It’s called op4j: Bending the Java spoon.  It is a Java library aimed at improving quality, semantics, cleanness and readability of Java code, especially auxiliary code like data conversion, structure iteration, filtering, mapping, etc.

For example…

We have a list of string and all of the strings are dates in dd/MM/yyyy format and we wanted to convert them into java.util.Calendar objects. And some string may be null and we don’t want nulls to be included in final results and one more things, we don’t want dates in the futures, only the past ones in the final results.

So here three things we need to do:

  • Convert all the string dates in java.util.Calendar object
  • Remove nulls
  • Remove futures dates.

So let’s see how we can do it in normal java.


                List<String> list = new ArrayList<String>();
		list.add("17/10/2012");
		list.add("16/10/2011");
		list.add("15/10/2010");
		list.add("14/10/2007");
		list.add(null);
		list.add("13/10/2009");

		Calendar now = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		Calendar calendar = Calendar.getInstance();

		Set<Calendar> set = new LinkedHashSet<Calendar>();
		Date date = null;
		for (String element : list) {
			if (element != null) {
				try {
					date = dateFormat.parse(element);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				calendar.setTimeInMillis(date.getTime());
				if (!calendar.after(now)) {
					set.add(calendar);
				}
			}
		}

Same thing we can do it with op4j but writing only 2 line of code


Calendar now1 = Calendar.getInstance();
		Set set1 = Op.on(list).toSet()
				.map(FnString.toCalendar("dd/MM/yyyy"))
				.removeAllNullOrTrue(FnCalendar.after(now1)).get();

and a lot of other example are here: http://www.bendingthejavaspoon.com/

and adding op4j

<dependency>
	<groupId>org.op4j</groupId>
	<artifactId>op4j</artifactId>
	<version>1.2</version>
</dependency>

Happy Coding !!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s