Monday, 8 February 2021
Saturday, 7 December 2019
Thread Pool-Executor Service
December 07, 2019 / with 6 comments /
Implementing Executor Service in Java
When you want to get the data from the various services and make the service calls concurrently.
ExecutorService executors = Executors.newFixedThreadPool(2); //creats the thread pool of size 2
//Using method reference
Callable<Map<Integer, String>> service1cal= service1::getData;
//Using lamda expression
Callable<List<SomeBean>> service2cal= ()-> {
service2.getData(input1);
};
service2.getData(input1);
};
Future<Map<Integer, String>> service1f= executors.submit(service1cal);
Future<List<SomeBean>> service2f= executors.submit(service2cal);
Map<Integer, String> service1datamap=service1f.get(); //its a blocking statement ,it will make the main thread to wait until its ex
List<SomeBean> service2list=service2f.get();
executors.shutdown();
Monday, 22 July 2019
Sort HashMap By Keys
July 22, 2019 / with No comments /
Sorting HashMap by Keys using TreeMap and Comparator
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import com.kanth.bo.Employee;
public class HashMapSortKeys {
public static void main(String[] args) {
Map<String, Employee> unsortedMap = getEmpData();
Map<String, Employee> treeMap = new TreeMap<String, Employee>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.parseInt(s1) > Integer.parseInt(s2) ? 1 : -1;
}
});
unsortedMap.forEach((k, v) -> {
treeMap.put(k, v);
});
System.out.println("after sorting " + treeMap.size());
treeMap.forEach((k, v) -> {
System.out.println("key is " + k + "Value is " + v);
});
}
public static Map<String, Employee> getEmpData() {
String proj1[] = { "Singtel", "Ericson", "STC", "TM" };
String proj2[] = { "Singtel", "Cisco", "STC", "TM" };
String proj3[] = { "STC", "TM" };
Map<String, Employee> empData = new HashMap<>();
empData.put("1234", new Employee("Ramakanth", 31000d, "SMP", 27, proj1));
empData.put("112", new Employee("Sanjay", 40000d, "IOT", 27, proj1));
empData.put("578", new Employee("Anil", 50000d, "SMP", 28, proj3));
empData.put("889", new Employee("Raju", 30000d, "SMP", 27, proj2));
empData.put("762", new Employee("Vijay", 20000d, "IOT", 32, proj1));
empData.put("687", new Employee("Eswar", 27000d, "SMP", 30, proj2));
empData.put("579", new Employee("Satish", 21000d, "ADP", 26, proj3));
return empData;
}
}
class Employee {
private String name;
private Double salary;
private String Dept;
private Integer age;
private String[] projects;
//getters and setters
}
Sort HashMap By Values
July 22, 2019 / with No comments /
Sort the HashMap by Values using comperator and Entry Object
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.Set;
import com.kanth.bo.Employee;
public class HashMapSortByValues {
public static void main(String[] args) {
Map<String, Employee> unsortedMap = getEmpData();
Set<Entry<String, Employee>> dataset = unsortedMap.entrySet();
List<Entry<String, Employee>> mylist = new ArrayList<>(dataset);
//Comparator for sorting by salary for Employee Object
Comparator<Entry<String, Employee>> myvalucomp = new Comparator<Entry<String, Employee>>() {
@Override
public int compare(Entry<String, Employee> o1, Entry<String, Employee> o2) {
return o1.getValue().getSalary() < o2.getValue().getSalary() ? 1 : -1;
}
};
//sorting based on comparator
Collections.sort(mylist, myvalucomp);
//LinkedHashMap -- as it maintains the order
Map<String, Employee> sortedMap = new LinkedHashMap<>();
sortedMap = mylist.stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
// sorted by values
sortedMap.forEach((k, v) -> {
System.out.println("The key is " + k + " values " + v);
});
}
public static Map<String, Employee> getEmpData() {
String proj1[] = { "Singtel", "Ericson", "STC", "TM" };
String proj2[] = { "Singtel", "Cisco", "STC", "TM" };
String proj3[] = { "STC", "TM" };
Map<String, Employee> empData = new HashMap<>();
empData.put("1234", new Employee("Ramakanth", 31000d, "SMP", 27, proj1));
empData.put("112", new Employee("Sanjay", 40000d, "IOT", 27, proj1));
empData.put("578", new Employee("Anil", 50000d, "SMP", 28, proj3));
empData.put("889", new Employee("Raju", 30000d, "SMP", 27, proj2));
empData.put("762", new Employee("Vijay", 20000d, "IOT", 32, proj1));
empData.put("687", new Employee("Eswar", 27000d, "SMP", 30, proj2));
empData.put("579", new Employee("Satish", 21000d, "ADP", 26, proj3));
return empData;
}
}
class Employee {
private String name;
private Double salary;
private String Dept;
private Integer age;
private String[] projects;
//getters and setters
}
Thursday, 13 June 2019
Stream API
June 13, 2019 / with No comments /
Java 8 Stream API Basic Examples.
Let us understand the few ways where we can use java 8 streams to solve the problems.github link: https://github.com/RamakanthB/Java8Lamda-Streams
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamBasics {
public static void main(String[] args) {
List<Employee> emplist = getAllEmpData();
System.out.println("*********** Print All Employees Details ***********");
emplist.stream().forEach(System.out::println);
System.out.println("*********** Only Name of Employees ***********");
emplist.stream().map(s -> s.getName()).forEach(System.out::println);
System.out.println("*********** Only DEV Dept Employees ***********");
emplist.stream().filter(s -> "DEV".equals(s.getDept())).map(s ->
s.getName()).forEach(System.out::println);
System.out.println("***** Only DEV Dept ans store in new List of Beans*****");
List<Employee> devemplist = emplist.stream().filter(s -> "DEV".equals(s.getDept()))
.collect(Collectors.toList());
devemplist.stream().forEach(System.out::println);
System.out.println("*********** Only STC Project ***********");
long count = emplist.stream().flatMap(s ->
Arrays.stream(s.getProjects())).peek(System.out::println)
.filter(s -> s.equals("STC")).count();
System.out.println("People who are assigned with STC " + count);
System.out.println("*********** Highest salary ***********");
Optional<Employee> higestSal = emplist.stream().reduce((s1, s2) -> s1.getSalary() >
s2.getSalary() ? s1 : s2);
higestSal.ifPresent(System.out::println);
}
public static List<Employee> getAllEmpData() {
List<Employee> emplist = Arrays.asList(
new Employee("Ramakanth", 20000d, "DEV", 27, new String[] { "STC", "TMOB", "GPAYROLL" }),
new Employee("Sanjay", 10000d, "TES", 27, new String[] { "IBM", "ACC" }),
new Employee("Wasim", 17000d, "DEV", 27, new String[] { "STC", "TMOB" }),
new Employee("Umakanth", 8000d, "AID", 25, new String[] { "NXP" }),
new Employee("Pavan", 30000d, "DEV", 27, new String[] { "STC", "CGI" }),
new Employee("Vijay", 10000d, "TES", 27, new String[] { "TMOB", "GPAYROLL" }),
new Employee("Debasis", 17000d, "DEV", 27, new String[] {"GPAYROLL" }),
new Employee("Siva", 8000d, "AID", 27, new String[] { "STC", "TMOB" }),
new Employee("Hema", 40000d, "DEV", 32, new String[] { "STC", "TMOB", "GPAYROLL" }),
new Employee("Deepak", 22000d, "TES", 31, new String[] { "TMOB", "GPAYROLL" }));
return emplist;
}
}
class Employee {
private String name;
private Double salary;
private String Dept;
private Integer age;
private String[] projects;
public String getName() {
return name;
}
public String[] getProjects() {
return projects;
}
public void setProjects(String[] projects) {
this.projects = projects;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String getDept() {
return Dept;
}
@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + ", Dept=" + Dept + ", age=" + age + ", projects="
+ Arrays.toString(projects) + "]";
}
public Employee(String name, Double salary, String dept, Integer age, String[] projects) {
super();
this.name = name;
this.salary = salary;
Dept = dept;
this.age = age;
this.projects = projects;
}
public void setDept(String dept) {
Dept = dept;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Friday, 9 November 2018
Joining the strings in java 8
November 09, 2018 / with 5 comments /
Everyone will experience the scenario where we need to join the strings in java .
These are the few ways we can do String concatenation in java 8.
Lets say we have 5 strings we want to make it 1 string with ',' separator .
String finalval = String.join(",", "First", "Second", "Third", "Forth");
output : First,Second,Third,Forth
In Case of array of String then,
String arry[] = { "Mango", "Apple", "Papaya" };
String finalval = String.join("-", arry);
output : Mango-Apple-Papaya
Lets say we want to append string to create IN params for SQL Query then,
import java.util.StringJoiner;
StringJoiner sj = new StringJoiner("','", "('", "')");
sj.setEmptyValue("It is empty");
System.out.println(sj.toString()); //prints 'It is empty' as nothing is there to join
sj.add("nike").add("Reebok").add("Puma").add("LV").add("Gucci");
System.out.println(sj.toString());
output:('nike','Reebok','Puma','LV','Gucci')
We can merge the two StringJoiners,
StringJoiner sj2 = new StringJoiner(",");
sj2.add("Fossil");
sj.merge(sj2);
System.out.println(sj.toString());
output:('nike','Reebok','Puma','LV','Gucci','Fossil')
Wednesday, 24 October 2018
Singleton Design Pattern in Java
October 24, 2018 / with No comments /
- singleton is a way to restrict only one object per a class
There are multiple ways of creating a singleton object 1) eager initialized singleton
public class MySingelton1 {
private final static MySingelton1 myobj =new MySingelton1();
private MySingelton1() {
System.out.println("new instance created MySingelton1");
}
public static MySingelton1 getMyobj() {
return myobj;
}
}
This class object is created only once during the loading time itself
2) lazy initialized singleton
public class MySingelton2 {
private static volatile MySingelton2 myobj=null;
private MySingelton2() {
System.out.println("new instance created MySingelton2");
}
public static MySingelton2 getMyobj() {
if (myobj == null) {
synchronized (MySingelton2.class)
{
if (myobj == null) {
myobj = new MySingelton2();
}
}
}
synchronized (MySingelton2.class)
{
if (myobj == null) {
myobj = new MySingelton2();
}
}
}
return myobj;
}
}
This class object is cretaed only once when you called the getMyobj() method for the first time.
Subscribe to:
Posts (Atom)