Tuesday, 10 October 2017

Different ways to sort Array list in Java

In this post, I am going to explain how to sort an array list in Java in different ways.

a.   By using the sort method provided by List interface
b.   By using Collections.sort method
c.   Sort elements using streams

By using sort method of List interface
List interface introduces the sort method from Java1.8 onwards. To make the List interface backward compatible, it made the sort method as default.

default void sort(Comparator<? super E> c)

sort method takes a comparator as argument and sort the list as per the comparator implementation.
 emps.sort(new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });


Above snippet sort employees based on country.

If you pass the comparator as null, then sort method takes the natural ordering of elements. Natural ordering takes the comparable method implementation.

emps.sort(null);

Above snippet sort the elements based on Comparable implementation of Employee class.

Find the below complete working application.


Employee.java
package com.sample.model;

public class Employee implements Comparable<Employee> {

 private int id;
 private String name;
 private String country;

 public Employee(int id, String name, String country) {
  super();
  this.id = id;
  this.name = name;
  this.country = country;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", country=" + country + "]";
 }

 @Override
 public int compareTo(Employee emp) {
  if (emp == null)
   return 1;
  return this.id - emp.id;
 }

}


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  emps.sort(new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

  emps.stream().forEach(System.out::println);

  System.out.println("\nSince comparator is not provided, it takes comparable implementation");
  System.out.println("*********************************");
  emps.sort(null);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]

Since comparator is not provided, it takes comparable implementation
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]

java.util.Collections class provided sort method to sort elements of list.

public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list,Comparator<? super T> c)

First form of sort method sorts the elements in their natural ordering, for ex: for integers ascending order is the natural order. You can specify the natural
ordering of elements by implementing Comparable interface.


Below snippet sort the elements based on employee country.
  Collections.sort(emps, new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

Below snippet sort the elements by natural ordering.

Collections.sort(emps);

Find the below working application.


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  Collections.sort(emps, new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

  emps.stream().forEach(System.out::println);

  System.out.println("\nSince comparator is not provided, it takes comparable implementation");
  System.out.println("*********************************");
  Collections.sort(emps);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]

Since comparator is not provided, it takes comparable implementation
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]


If you do not specify the comparator, then sort method sort the elements based on the Comparable implementation.

Below snippet sort the elements based on the Comparable implementation of Employee class.
Collections.sort(emps, null);


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  Collections.sort(emps, null);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]

c. Sort elements using streams
Below snippet sort the elements using country of the employee.
emps.stream().sorted(comparing(Employee::getCountry)).collect(Collectors.toList());


Test.java
package com.sample.sort;

import static java.util.Comparator.comparing;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  emps = emps.stream().sorted(comparing(Employee::getCountry)).collect(Collectors.toList());
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]




ABAP: Function Builder

Function modules are the reusable components in ABAP program. If you are from Java, C, CPP background, function modules are just like functions. Function module takes input, process it and return the output.

How to open Function Builder?
SAP GUI provides UI based tool to define function modules. Use the transaction code 'SE37' to open function builder.

Below step-by-step procedure explains how to create a function module using function builder.

Step 1: Use the transaction code ‘SE37’ to open function builder.

Step 2: First we need to create function group. Function group is a container that maintains function modules.


Go to GOTO ->  Function Groups -> Create Group.
It opens below window, give the
‘Function group’ name as ‘Z_MATH_UTIL_FUNCTIONS
‘Short text’ as ‘All the mathematical functions kept here’.
Press Save button. It opens below window.

I do not want to save this function group in any package, so click on the button ‘Local Object’.
Step 3: Now enter the function module name as ‘Z_SUM_OF_NUMBERS’.
Click on ‘Create’ button.

It opens below window. Update function group name and short text.
Click on ‘Save’ button.

It opens below window.
Once you press on ‘Activate’ button. It opens activation window.

Select all the objects and activate them.

Step 4: Define input arguments to the function module.
Click on the ‘Import’ tab.
I defined two variables of type Int.

Step 5: Define output parameter of function module.
Step 6: Go to ‘Source code’ tab and update the source code. I just added below statement.

Z_SUM = Z_VALUE1 + Z_VALUE2.
Activate the function module.

Step 7: Now you can test the function module by pressing F8 (or) by clicking on the button shown in below image.
Enter input values and press F8 (or) click on Execute button.
You can able to see the output.
How to call function module ‘Z_SUM_OF_NUMBERS’?
Open ‘ABAP Editor’ using the transaction ‘SE38’.

Give the program name as ‘Z_TEST_SUM’ and click on ‘Create’ button.
It opens below window.
Give some Title, Select the Type as ‘Executable program’. Press Save button.
It opens other window, click on the button ‘Local Object’.

It opens below window.
Click on the button ‘Pattern’.

It opens below window. Select the radio button ‘CALL FUNCTION’ and give the function name as ‘Z_SUM_OF_NUMBERS’. Press Ok button.
Now it generates some default code.
Update the code like below.

Z_TEST_SUM
*&---------------------------------------------------------------------*
*& Report Z_TEST_SUM
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT Z_TEST_SUM.

DATA sum_of_two_numbers TYPE I.

CALL FUNCTION 'Z_SUM_OF_NUMBERS'
  EXPORTING
    Z_VALUE1       =  5
    Z_VALUE2       =  6
 IMPORTING
   Z_SUM          = sum_of_two_numbers
  .

Write: ' sum_of_two_numbers : ',  sum_of_two_numbers.

Check and activate the program.


Execute the program, you can able to see below output.



Previous                                                 Next                                                 Home

Thursday, 5 October 2017

ABAP: Foreign Key relationship

This is continuation to my previous post. In my previous post, I created below two database tables.

·       ZSTUDNT
·       ZTEACHINGFACULTY

In this post, I am going to show how to set the foreign key relationships between database tables.

I am going to create a table ZFACULTY_RATING and going to set the foreign key relationship with ZSTUDNT and ZTEACHINGFACULTY.

Firs create the table ZFACULTY_RATING.

ZFACULTYRATING
faculty_id
student_id
faculty_rating




Field
Data Element
faculty_id
ZFACULTY_ID
student_id
ZSTUDENT_ID
faculty_rating
ZFACULTY_RATING

Use the transaction ‘SE11’ to open ABAP dictionary.


Give the table name as ‘ZFACULTYRATING’ and click on Create button.

Update the short description as ‘Faculty Rating table’
Set the Delivery class as Application Table
Set the Data Browser/Table View Editing field to ‘Display/Maintenance allowed’.
Click on Fields tab.
Since this is an Application table, we need to add MANDT field here. Add all the fields and data elements of ZFACULTYRATING table.
Select the fields MANDT and faculty_id as key.
Press Enter, it will populate other information (data type, length etc.,) like below.

Go to Extras -> Enhancement Category
Press Ok.
Select the option ‘Can Be Enhanced (Deep)’ an click on the button Copy.
Save the changes.

Click on ‘Technical Settings’.
Add data class as APPL0’.
Set the ‘Size Category’ to 1.

Save settings.

Activate the table ‘ZFACULTYRATING’.

Adding the foreign key constraint to the table ZFACULTYRATING

Open the table ‘ZFACULTYRATING’ in Edit mode.

Go to ‘Input Help/Check’ tab.

Select the FACULTY_ID field and click on the ‘key icon’ button.
It opens below window.
Update the Short text as ‘Faculty id referring to faculty table’.

Click on the Check table input box, it opens the list of tables.
Select ‘ZTEACHINGFACULTY’ field.

Click on ‘Create Proposal’ button.
Press the button ‘Copy’.

That’s it, you are done.

Add foreign key constraint to the field STUDENT_ID.
Select the STUDENT_ID field and click on the ‘key icon’ button.
Add ZStudnt table.
Now the screen change like below.

Press Save button and activate the table.

That’s it you are done.



Previous                                                 Next                                                 Home