Java Priority Queue Example

Priority Queue introduced as part of Java 1.5 and it is an unbounded queue based on a priority heap.

Elements in the queues are in natural ordering or by a comparator provided by at queue construction time.

It does not allow null values.

Example:


Here is one simple example to create a PriorityQueue to store order details and our priority is to process premium orders first.

package com.vinod;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueTest {

public static void main(String[] args) {

// Creating Priority Queue and inserting objects
Comparator<String> pqc = new PQueueComparator();
Queue<String> orderQueue = new PriorityQueue<String>(100, pqc);
orderQueue.add("order number 1");
orderQueue.add("order number 2 premium");
orderQueue.add("order number 3");
orderQueue.add("order number 4");
System.out.println("Order details after insertion");
for (String orderDetail : orderQueue) {
System.out.println(orderDetail);
}
System.out.println("priority order " + orderQueue.poll());
}

}

class PQueueComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (s1.length() < s2.length()) {
return 1;
}
if (s1.length() > s2.length()) {
return -1;
}

return 0;
}

}

Ouput:

Order details after insertion
order number 2 premium
order number 1
order number 3
order number 4
priority order order number 2 premium

What is Open/Closed Principle (OCP) ?

According to GoF design pattern authors "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

Example

In the below code we are handling ADD and SELECT operations and there is a chance to come additional operations like update or delete. So this curOperation method is not closed for modification.
package com.vinod;

public class CrudOperation {

public String crudOperation(String details, String operation) {
String result = null;
if (operation.equals("ADD")) {
// call add logic
result = details + "Inserted";
}
if (operation.equals("SELECT")) {
// call select logic
result = details + "details";
}
return result;
}
}
The same task we can define another way
package com.vinod;

/**
 *@authorvinod.kumaran
 *
 */
public interface Operation {
abstract String executeOperation(String data);
}


package com.vinod;

public class SelectOperation implements Operation {

@Override
public String executeOperation(String data) {
return "Selected data is" + data;
}

}
package com.vinod;

public class AddOperation implements Operation {

@Override
public String executeOperation(String data) {
return "Record inserted";
}

}

package com.vinod;

public class UpdateOperation implements Operation {

@Override
public String executeOperation(String data) {
// TODO Auto-generated method stub
return data+"Updated";
}

}
So the above three classes are closed and the interface we can use it for further implementations 
package com.vinod;

/**
 *@authorvinod.kumaran
 *
 */
public class OperationTest {
public static void main(String[] args) {
Operation select = new SelectOperation();
Operation add = new AddOperation();
Operation update = new UpdateOperation();
System.out.println(select.executeOperation("helloworld"));
System.out.println(add.executeOperation("helloworld"));
System.out.println(update.executeOperation("helloworld"));

}
}
 

What is coupling and cohesion?

Coupling

In software development perspective coupling is the degree of a module or class is tied directly to others.We can reduce the coupling via implementing intermediate components like Spring IOC, business delegates etc.

Cohesion


We don't want a single class to perform all the tasks like validation, business logic, data acces logic etc.In order to create a  more cohesive system from the higher and lower level perspectives,you need to break out the various needs into separate classes.
Interfaces, Implementation, Validator, Data access classes etc.

Vertical vs Horizontal scaling

Vertical vs Horizontal scaling

Vertical scaling means adding more resources(CPU/RAM/DISK) to your server (database or application server is still remains one).

Horizontal scaling means adding more processing units (phyiscal machine) to your server (infrastructure be it application web/server or database).

Java FileNameFilter Example to list files with specific name or extension

Instances of classes that implement java.io.FilenameFilter interface are used to filter file names from a directory. We can list out a directory and filter files based on the name start with, ends with etc.
Here is one example list out the files which are starting with File and extension of .java from the current directory.

Example

package com.vinod.filetest;

import java.io.File;
import java.io.FilenameFilter;

/**
 *@authorvinod.kumaran
 *
 */
public class FileFilterExample {

public static void main(String[] args) {

File currentdir = new File(System.getProperty("user.dir")
+ "/src/main/java/com/vinod/filetest");
File[] listFiles = currentdir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.startsWith("File") && name.endsWith(".java"));
}
});
for (File listFile : listFiles) {
System.out.println(listFile.getName());
}
}

}
Output
FileFilterExample.java
 

OpenCSV creating csv records Example

Example

package com.vinod.opencsv;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVWriter;

public class OpenCSVExample {
private static final char DELIMITER = ',';

/**
    *@param args
    */
public static void main(String[] args) {
StringWriter writer = new StringWriter();
CSVWriter csvWriter = null;

// Creating student objects
Student st1 = new Student("1", "vinod");
Student st2 = new Student("2", "raghav");
Student st3 = new Student("3", "shariff");

// Creating student object list
List studentList = new ArrayList();
studentList.add(st1);
studentList.add(st2);
studentList.add(st3);

try {

// Creating csvWriter object
csvWriter = new CSVWriter(writer, DELIMITER, 
CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER, "\n");

List records = new ArrayList(10);

// Iterating student list and put it into new String array List
for (Student stud : studentList) {
List record = Arrays.asList(stud.getId(), stud.getName());

String recordArray[] = new String[record.size()];
record.toArray(recordArray);
records.add(recordArray);
}

// Writing string arrayList in to Stringwriter

csvWriter.writeAll(records);

// Spring String writer as csv records
System.out.println("CSV Details");
System.out.println(writer.toString());

} catch (Exception e) {
e.printStackTrace();
}

}
}

class Student {
private String id;
private String name;

public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}

public String getId() {
return id;
}

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

public String getName() {
return name;
}

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

}
Output
CSV Details
"1","vinod"
"2","raghav"
"3","shariff"

Java Ehcache Simple Example

Ehca  che is an open source framework for caching objects. It is very simple and most widely used.
Here we will see one simple example to put one Student object in to cache and using that object from cache.
See more about Ehcache
1. Add below maven dependency
<dependency>
<groupid>net.sf.ehcache</groupid>
<artifactid>ehcache</artifactid>
<version>2.8.0</version>
</dependency>
2. Create a Pojo class
public class Student implements Serializable {

private static final long serialVersionUID = -8642556460186434431L;
private Integer studId;
private String firstName;
private String lastname;

public Student(
Integer emplId, String firstName, String lastname) {
super();
this.studId = emplId;
this.firstName = firstName;
this.lastname = lastname;
}
// Getters and setters
3. Create ehcache.xml configuration
This file needs to be placed in your resources folder (src/main/resources)
<ehcache name="StudentCache">
<defaultcache diskexpirythreadintervalseconds="120" diskpersistent="false"
diskspoolbuffersizemb="30" eternal="false" maxelementsinmemory="10000"
maxelementsondisk="10000000" memorystoreevictionpolicy="LRU" overflowtodisk="true"
timetoidleseconds="120" timetoliveseconds="120">
<cache eternal="false" maxelementsinmemory="100" maxelementsondisk="0"
memorystoreevictionpolicy="LFU" name="students" timetoidleseconds="120"
timetoliveseconds="0"></cache>
</defaultcache>
</ehcache>
3. Create a class to load cache configuration
package com.vinod.ehcache;

import java.io.InputStream;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 *@authorvinod.kumaran
 *
 */
public class StudentEHCache {

private static final CacheManager cacheManager;
private Ehcache studentCache;

// Loading ehcache config file and creating CacheManager.
static {

ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("ehcache.xml");
cacheManager = CacheManager.create(resourceAsStream);
}

public StudentEHCache() {
studentCache = cacheManager.getEhcache("students");
}

/**
    * Creating new Element to hold student object
    *
    *@param id
    *@param student
    */
public void addStudent(Integer id, Student student) {
Element element = new Element(id, student);
studentCache.put(element);
}

/**
    * Method to get Student object using id.
    *
    *@param id
    *@return
    */
public Student getStudent(Integer id) {
Element element = studentCache.get(id);
if (element != null) {
return (Student) element.getValue();
}
return null;
}
}
4. Create a main class to test cache

package com.vinod.ehcache;

/**
 *@authorvinod.kumaran
 *
 */
public class StudentCacheTest {
private StudentEHCache simpleEHCacheExample;

public StudentCacheTest() {
simpleEHCacheExample = new StudentEHCache();
simpleEHCacheExample.addStudent(1, new Student(1, "Vinod", "Bangalore"));

System.out.println(simpleEHCacheExample.getStudent(1));

}

public static void main(String[] args) {
new StudentCacheTest();
}

}
5. Output  
Student [studId=1, firstName=Vinod, lastname=Bangalore]

 

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts