Grouping objects in a list

Use this simple line of code if you need to group a list of objects from a collection.

public class Field {

private Long id;

private String name;

private Long groupId;

// constructors ,getters and setters goes here

Field f1 = new Field(1l,"goutham",1l);
Field f2 = new Field(2l,"goutham",1l);
Field f3 = new Field(3l,"goutham2",2l);
Field f4 = new Field(4l,"goutham2",2l);
Field f5 = new Field(5l,"goutham3",3l);
Field f6 = new Field(6l,"goutham4",4l);<

List fields = Arrays.asList(f1,f2,f3,f4,f5,f6);
Map fieldsGroupedById =
(key,value) -> {
                 StringBuffer b = new StringBuffer();
                 value.forEach( (field ) -> b.append(field.getName()).append(" "));
                 System.out.println("key = "+key +" values = "+b.toString());

You should get the below output :

key = 1 values = goutham goutham 
key = 2 values = goutham2 goutham2 
key = 3 values = goutham3 
key = 4 values = goutham4
| Leave a comment

Sorting collections in Java 8 using Lambda

With introduction of java 8 lambdas it is very easy to sort collections .

Ex: Consider a class Person as below

public class Person{

private String name;
private String age:

// constructors
//getters and setters

Now sorting an list of persons based on their age is very easy . There is no need for a comparator class to be written.

List persons = new ArrayList();
persons.add( new Person("john",38));
persons.add( new Person("peter",23));
persons.add( new Person("sam",32));

persons.sort( (p1,p2) -> p1.getAge().compareTo(p2.getAge()));

| Leave a comment

JaxB and List wrapper (@XmlSeeAlso annotation usage)

JaxB cannot deserialise collections which is general handicap of JaxB . When your rest endpoint needs to send in a list of objects in xml you will need to wrap your collection in a wrapper object and this is is where GenericEntity<T> class of JaxB comes into place.

Your code would then look something like this below:

      public Response getAddresLists(Long personId) {  
           List<Address> lists = addressService.getAddressForPerson(personId);  
           GenericEntity<List<Address>> entity=new GenericEntity<List<Address>>(lists) {};  
           return Response.ok(entity).build();  

In case if you do not know the type of the object your collection holds ( your list is non generic ) then we will need to hack around to get this working.

I reimplemented the GenericEntity class to add a few more jaxb annotations to get it working .

 @XmlAccessorType (XmlAccessType.FIELD)  
 public class NonGenricEntity <T> {  
      private List<T> data;  
      public NonGenricEntity() {  
           // TODO Auto-generated constructor stub  
      public NonGenricEntity(List<T> myData) {  
  = myData;  
      public List<T> getObject() {  
           return data;  
      public void setMyData(List<T> myData) {  
  = myData;  

So when JaxB marshalls the object in the collection to XML @XmlSeeAlso annotation helps it to match the fields of the object to the type of class and you get the appropriate response.

| Leave a comment

Configuring Jackson Json provider in Talend ESB /Apache Karaf ( Apache CXF ).

Talend ESB uses apache CXF internally to as the rest service provider. Jackson provides good support for hibernate through its hibernate4module.

I did notice that inspite of configuring the provider in the blueprint.xml file correctly it was not being picked up and the internal json provider

that gets shipped along with apache cxf was being used. I could see that it was being registered , but not used.

One digging deeper into the implementation code apache cxf I noticed that it while marshalling the object it was looping through the providers and picking the first , remember list.get(0) method.

Luckily the onlyway to get around that is to not load the default provider . This ensures that only JacksonJsonProvider is registered and gets used.


      <cxf:bus id="bus">  
                <cxf:logging />  
             <entry key="skip.default.json.provider.registration" value="true"/>  
           <jaxrs:server address="/payment" id="paymentService">  
          <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />  
| Leave a comment

Learning Scala: Some Notes

Introduction to Scala notes:

Class: A class describes how you would want to represent a concept such as a customer. To have an instance of the concept to represent a specific person you have to instantiate the class with the new


scala> class Hello
defined class Hello

scala> new Hello()
res5: Hello = Hello@6d5cfb9

Contructor: body of the class defines the constructor

scala> class Hello {
| println(“Hello”)
| }
defined class Hello

scala> new Hello()

Parameters: You can pass values into an instance of a class using a parameter. You must specify the type
of parameter , it is visibile internally to the class instance during its lifetime and not accessible outside the instance.

scala> class Hello(message: String){
| println(message)
| }
defined class Hello

scala> new Hello(“Hello workd”)
Hello workd
res6: Hello = Hello@3275e8bc

scala> res6.message
<console>:14: error: value message is not a member of Hello

Immutable and Mutable Fields :
Field: hold state and is accessible from outside world

Difference between parameters and fields:
parameters are passed to a class and are only visible within a class
fields: exists inside the body of the class and are accessible from outside.

immutable field: use val keyword

scala> class Hello{
| val message: String =”HEllo”
| }
defined class Hello

scala> new Hello
res9: Hello = Hello@42a03285

scala> res9.message
res10: String = HEllo
non-immutable field : use var keyword
scala> class Hello{
| var message: String = “Hello”
| }
defined class Hello

scala> new Hello()
res11: Hello = Hello@4673b889

scala> res11.message
res12: String = Hello

scala> res11.message = “Hello world”
res11.message: String = Hello world

scala> res11.message
res13: String = Hello world


define a method it is of the format:
def methodName( variableName: scalaType): returnScalaType = method


scala> def echo( message: String): String = “Hello” + message
echo: (message: String)String

scala> echo(“Goutham”)
res16: String = HelloGoutham

Methods are evaluated everytime they are called , while fields are evaluated only during creation
Default and Named Arguments:

You can have default values when no value is passed to the method and specifically say which parameter we are passing into the method like last=”Rao”. It can be used in class constructors too

scala> def name( first: String=”Goutham” ,last: String=””): String = first + ” ” + last
name: (first: String, last: String)String

scala> name(last=”Rao”)
res17: String = Goutham Rao

Singleton object: Scala objects are used for creating Class Factories, Utility Methods, Constant Definitions

scala> object Hello{
| def message():String=”hello message”
| }

scala> Hello.message
res18: String = hello message

Case Classes:

In short are our domain/DTO classes. Compiler generates jvm specific convinience methods.
Every parameter in the case class is made into a field inside the class and is immutable. NO need to use the new keyword.

scala> case class Time(hours: Int=0, minutes: Int=0)
defined class Time

scala> val time = Time(9,0)
time: Time = Time(9,0)

scala> time.hours
res22: Int = 9

Performs value based equivalence by default

scala> val time = Time(9,0)
time: Time = Time(9,0)

scala> time == Time(9,0)
res19: Boolean = true

scala> time == Time(9,30)
res20: Boolean = false

scala> time == Time(9)
res21: Boolean = true

Case Object:
Singleton object of a domain model. Ony single instance of the case class is made available.

Apply and Unapply:
A type is a description of a concept in an application – A class is a type.
A term is a concrete representation of a type
– Any class instance ( or even an Object ) is a term
– A method is also a term , as it is also concrete and callable
When you call a term without specifying the method on it , it calls the apply method in background

scala> case class Time( hours : Int =9, mins:Int =0 )
defined class Time

scala> Time(9)
res23: Time = Time(9,0)


scala> Time.apply(9)
res24: Time = Time(9,0)

scala> res23 == res24
res25: Boolean = true

Thread saftey in Scala:
JVM has a well defined memory model with specific gurantees. Ex : a website selling books. Means there is a variable holding the stock inside the app. Two concerns with regards to threads:
– Synchronize-with: which thread is able to make the change and in what order
– Happens-Before: how does the other threads see this change

When you are writing scala there are two things we need to watch out for. The left hand side of the equals and the right hand side of the equals. ( the pointer and its value )

val me = new Person(“Jamie”, “Allen”)
^ ^
| |
name value

If pointer can be changed , then it is a var
if can’t be changed , then it is a val.

1.var pointing to a mutable state inside the class we are creating ( then there is mutability in both the pointer and inside of the reference . Not good )
2.val pointing to a mutable data

In both the conditions we need to defining locking mechanisms

3. A var pointing to an immutable state . In this case we have snapshots , if the state on the right hand side changes , then we will be pointing to a new instance of the state.We use the copy method to change state. We now have a var that is updated and this needs to be made visible to all threads. We do this using @volatile annotation
4. a val pointing to an immutable state

scala> case class Customer(first: String=””, last: String=””)
defined class Customer

scala> @volatile var customer = Customer(“Martin”, “Odersky”)
customer: Customer = Customer(Martin,Odersky)

scala> customer = customer.copy(last=”Charles”)
customer: Customer = Customer(Martin,Charles)


| Leave a comment

Installing SCALA on MAC OSX

Please follow the below steps to download and install scala.

  1. Download scala binary from : Download Scala
  2. Unzip to a folder of your choice.
  3. Set your environment path :
    export SCALA_HOME=/Users/gouthamrao/Documents/programs/scala-2.11.8
    export PATH=$PATH:$SCALA_HOME/bin

  4. Check installation:
    scala -version

    Scala code runner version 2.11.8 — Copyright 2002-2016, LAMP/EPFL

Set the path permanently by adding the above two lines to ~/.bashrc file so that the path gets set every time you open a new terminal window.


| Leave a comment

Scala Notes : martin odersky’s begining scala tutorial

2 – 3 – Lecture 1.3 – Evaluation Strategies and Termination (4-22)
talks of call by name and call by value method of evaluation. explaination with examples — understood

2 – 4 – Lecture 1.4 – Conditionals and Value Definitions (8-49)
talks of if else
two way of defining xpressions:

def : which is a call by name – the right hand side is evaluated at the time of usage
val : which is a call by value – the right hand side is evaluated at the point of definition.

2 – 5 – Lecture 1.5 – Example- square roots with Newton-‘s method (11-25)

2 – 6 – Lecture 1.6 – Blocks and Lexical Scope (8-00)
blocks are {} . the last statement determines the return value.
they are expressions themselves

visibility: values defined within the block are visibile inside
dfinition dfined putside the blocks are visibile inside the block

multi line expressions: use () or a + on the top line

2 – 7 – Lecture 1.7 – Tail Recursion (12-32)
a function that calls itself as the last action , the stack frame can be reused. Example: Euclid’s algorithm to find the greatest common diviser.
Factorial algorithm, stack cannot be reused, as the expression becomes bigger as it progresses
To avoid deep recursive stacks: most jvm limit to a couple of thousands of stack frames anyway.
So if your input data is susceptible to deep recursive chains it is better to reformulate the function to be tail recursive to avoid stack over flow exceptions.

4 – 1 – Lecture 3.1 – Class Hierarchies (25-50)
abstract classes: define , extend and instantiate. Concept similar to java , uses the keyword extends , override .
If no base class is defined then java.lang.Object is assumed to be the base class.
override for implementation of abstract definitions in the base classes is optional .
use of ‘object’ definition to create a singleton instance of a class.

4 – 2 – Lecture 3.2 – How Classes Are Organized (20-30)

use of keyword ‘package’,’import’. Some entities are imported automatically in any Scala program.
All members of Scala, java.lang and scala.Predef
Scala uses single inheritance model . Use ‘trait’ for multiple inheritance.
trait is like interfaces in java but can contain fields and concrete methods.
traits cannot have value parameters while classes can.
Scala class hierarchy: Scala.Any, Scala.AnyRef ( alias of java.lang.Object) , Scala.AnyVal

The Nothing type: it is at the bottom of scala’s type hierarchy. it is the subtype of every other type.
Exception handling is same as Java, return type is of type Nothing

4 – 3 – Lecture 3.3 – Polymorphism (21-09)
concentrates on Types. Principal concept here is type paramaterisation. i.e. classes and methods can have types as parameters.
Explains using a immutable list data structure called Cons-Lists.

5 – 1 – Lecture 4.1 – Functions as Objects (8-04)
functions are treated as objects in scala. they are nothing but objects with an apply method.
So a function with one argument is treated as an instance of Function1 class with an apply method. There are function classes that support upto 22 arguments.

5 – 2 – Lecture 4.2 – Objects Everywhere (19-07)
Explores the topic , is scala a pure object oriented language. In a pure oo language , every value is an object.
Explores how to implement primitive types ( Int, Boolean etc ) as classes

5 – 3 – Lecture 4.3 – Subtyping and Generics (15-02)
Subtyping came from oo and geenric from functional programming . In scala we combine the two and hence we need to be aware of the subtle differences.
If you understand why generics came into being in java then you can skip this lecture.

5 – 4 – Lecture 4.4 – Variance (Optional) (21-33)

5 – 5 – Lecture 4.5 – Decomposition (16-57)
An important problem in programming is decomposition. Let’s say you have a hierarchy of classes and you want to build a tree like datastructure from the instances of these classes . How do you build such a tree and how do you find out what kind of elements are stored in the tree and how do you access the data stored in these elements. This is the problem of decomposition and will be explored in detail using examples.

6 – 6 – Lecture 5.6 – Reasoning About Concat (13-00)

Mathematical induction: is a mathematical proof technique. Step 1 , prove for one natural no , second step, prove equation applies for the next natural no. I.e what applies for n also applies for n+1 .
Referential transparency: An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program (in other words, yielding a program that has the same effects and output on the same input). The opposite term is referential opacity.
7 – 1 – Lecture 6.1 – Other Collections (20-45)
Start with sequences. Introduces vector .. which is a 32 bit array .. once it gets full .. it then holds pointers to another 32 arrays.. this is a shallow implementation of a tree.. means has access to elements.. in list first element has faster access than the middle element. If accesss patterns are linear , then lists are better. if access pattern is like that of a map or filter then vector is preferable.
Vectors like lists are immutable

| Leave a comment