sort by id , name -custom sorting

Student.java:

package com.me.pack;

import java.util.Comparator;

@SuppressWarnings(“rawtypes”)
public class Student implements Comparable {
private int id;
private String name;
private float sal;

public static final Comparator idComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id – o2.id;
}
};

public static final Comparator nameComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.name.compareTo(o2.name);
}
};

public static final Comparator salComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return (int) (o1.sal – o2.sal);
}
};

public static final Comparator comp=
(Student s1, Student s2) -> s1.getName().compareTo(s2.getName());

@Override
public int compareTo(Student arg0) {
// TODO Auto-generated method stub
return this.id – arg0.id;
}

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 float getSal() {
return sal;
}

public void setSal(float sal) {
this.sal = sal;
}

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

@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, sal=” + sal + “]”;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(sal);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(sal) != Float.floatToIntBits(other.sal))
return false;
return true;
}

}

 

Test.java:

package com.me.pack;

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

public class ComparatorStudentLamda {
public static void main(String[] args) {
Student student = new Student(125, “bcv”, 546.09f);
Student student2 = new Student(123, “mno”, 123.09f);
Student student3 = new Student(130, “fgh”, 74357.09f);

List list = new ArrayList(Arrays.asList(student, student2, student3));
for (Student studenttemp : list) {
System.out.println(studenttemp);
}
System.out.println(“—————–“);
Collections.sort(list, Student.idComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.nameComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.salComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}
}
}

 

 

Invoke from java8:
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}

 

output:

Student [id=125, name=bcv, sal=546.09]
Student [id=123, name=mno, sal=123.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
Picked up _JAVA_OPTIONS: -Xmx512M

refer : http://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-examplehttp://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-
example

http://javarevisited.blogspot.in/2014/01/java-comparator-example-for-custom.html

Advertisements

Java-8 Predicates

You can get plenty good enough points here:

https://www.javabrahman.com/java-8/java-8-java-util-function-predicate-tutorial-with-examples

 

 

package com.me.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Java8PredicateTest2 {
public static void main(String[] args) {
Predicate predicate= even -> even%2==0;
List integers =new ArrayList(Arrays.asList(123,120,151,186,124));
List integersEven= filterList(integers,predicate);
integersEven.forEach(System.out::println);
}

private static List filterList(List integers, Predicate predicate) {
// TODO Auto-generated method stub
List integerstemp=new ArrayList();
for(Integer integer:integers){
if(predicate.test(integer)){
integerstemp.add(integer);
}
}
return integerstemp;
}
}

 

output:
120
186
124
Picked up _JAVA_OPTIONS: -Xmx512M

 

package com.me.pack;

import java.util.function.Function;
import java.util.function.Predicate;

public class Java8PredicateTest {
public static void main(String[] args) {
Predicate male =
h -> h.getName().equals(“madhu”) && “male”.equals(h.getGender());
Predicate female =
h -> h.getName().equals(“ammu”) && “female”.equals(h.getGender());

Function maleStyle =
s -> “Hi, You are male and age ” + s.getName();

Function femaleStyle =
s -> “Hi, You are female and age ” + s.getName();

HumanBeing s1 = new HumanBeing(“madhu”, “male”);
if (male.test(s1)) {
System.out.println(s1.predicateCustomFun(maleStyle));
} else if (female.test(s1)) {
System.out.println(s1.predicateCustomFun(femaleStyle));
}
}
}

 

package com.me.pack;

import java.util.function.Function;

public class HumanBeing {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public HumanBeing(String name, String gender) {
super();
this.name = name;
this.gender = gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String predicateCustomFun(Function maleStyle){
return maleStyle.apply(this);
}
}

 

output:
Picked up _JAVA_OPTIONS: -Xmx512M
Hi, You are male and age madhu

Java -8 stream package

package com.java8.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AllAnyNoneExample {
public static void main(String[] args) {
Predicate predicate = n -> n % 2 == 0;
List integers = Arrays.asList(102, 23, 45, 63, 90, 64, 23, 45);

// allmatch anymatch nonematch
System.out.println(integers.stream().allMatch(predicate));
System.out.println(integers.stream().anyMatch(predicate));
System.out.println(integers.stream().noneMatch(predicate));

// collect
List strings = new ArrayList(Arrays.asList("bcd", "cdf", "hdsbhjds", "hdfc"));
String op = strings.stream().collect(Collectors.joining("--"));
System.out.println(op);

// concat
List stringsIn1 = new ArrayList(Arrays.asList("icici", "hdfc"));
List stringsIn2 = new ArrayList(Arrays.asList("sbi", "kotak"));
Stream opConcat = Stream.concat(stringsIn1.stream(), stringsIn2.stream());
opConcat.forEach(s -> System.out.println(s));

// count
long l = integers.stream().count();
System.out.println(l);

// distinct
long l2 = integers.stream().distinct().count();
System.out.println(l2);

// predicate and filter
Predicate predicate2 = s -> s % 10 == 0;
integers.stream().filter(predicate2).forEach(s -> System.out.println(s));

// finAny and finaLast findFirst
String string = strings.stream().findAny().get();
System.out.println(string);

// flatMap
Integer[][] intDArray = { { 3, 24 }, { 3, 4 }, { 5, 6 } };
Arrays.stream(intDArray).flatMap(row -> Arrays.stream(row)).filter(n -> n % 2 == 0)
.forEach(s -> System.out.println(s + "---"));

Arrays.stream(intDArray).flatMap(row -> Arrays.stream(row)).filter(n -> n % 3 == 0)
.forEach(s -> System.out.println(s));

// forEach and forEachOrdered
Integer[] integersList = { 12, 34, 98, 212, 456, 234, 658, 213, 3543, 54654, 6, 43 };
Arrays.stream(integersList).filter(num -> num % 2 == 0).forEach(s -> System.out.print("--" + s));
Arrays.stream(integersList).filter(num -> num % 2 == 0).forEachOrdered(s -> System.out.print("--" + s));

// generate and limit
Stream.generate(Math::random).limit(10).forEach(s -> System.out.print(s));

// iterate
Stream stream = Stream.iterate(1, n -> n * 2).limit(5);
stream.forEach(s -> System.out.print(s + " "));

// map()
List list = Arrays.asList(1, 2, 3, 4);
list.stream().map(num -> num * 2).forEach(s -> System.out.println("__-" + s));

List listMinMax = new ArrayList(Arrays.asList("G", "B", "M", "O", "P", "s"));
String max = listMinMax.stream().max(Comparator.comparing(String::valueOf)).get();
String min = listMinMax.stream().min(Comparator.comparing(String::valueOf)).get();
System.out.println(max + "--" + min);

// peek
listMinMax.stream().peek(s -> System.out.println(s + "ABAP")).collect(Collectors.toList());

// reduce
int[] reduceArray = { 2, 6, 9, 25, 46 };
int sum = Arrays.stream(reduceArray).reduce(0, (x, y) -> (x + y));
System.out.println(sum);

// skip
int[] aSkip = { 12, 34, 52, 16, 66 };
Arrays.stream(aSkip).skip(3).forEach(s -> System.out.println(s + "---"));

// sorted
Map mapValues = new HashMap();
mapValues.put("no1", "123");
mapValues.put("no10", "hgf");
mapValues.put("mky", "sadfsa");
mapValues.put("tre", "34532");
mapValues.put("gds", "gg5y");
mapValues.put("sdfds", "sdfds");

// sorting based on key
mapValues.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
.forEach(s -> System.out.println(s.getValue() + "---" + s.getKey()));

// sorting based on value
mapValues.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
.forEach(s -> System.out.println(s.getValue() + "---" + s.getKey()));

String[] stringsNames = new String[]{"dfg","mno","cfx"};
Object[] obj = Stream.of(stringsNames).toArray();
for(Object object:obj){
System.out.println("---"+object);
}

}
}

false
true
false
bcd–cdf–hdsbhjds–hdfc
icici
hdfc
sbi
kotak
8
6
90
bcd
24—
4—
6—
3
24
3
6
–12–34–98–212–456–234–658–54654–6–12–34–98–212–456–234–658–54654–60.90594481675002210.81813738818315030.50438793979534930.58841494828841320.229276714851393230.053862502898993080.73554686557288540.46758853420518830.095253156593703040.67151235875973671 2 4 8 16 __-2
__-4
__-6
__-8
s–B
GABAP
BABAP
MABAP
OABAP
PABAP
sABAP
88
16—
66—
gg5y—gds
sadfsa—mky
123—no1
hgf—no10
sdfds—sdfds
34532—tre
123—no1
34532—tre
gg5y—gds
hgf—no10
sadfsa—mky
sdfds—sdfds
—dfg
—mno
—cfx
Picked up _JAVA_OPTIONS: -Xmx512M

JAVA-8 Features

Default method in Interface

Why we need default method in interface.

  • In general Interface is a collection of un-implemented methods i.e only abstract methods.Rules before java-8 are
  • //All methods are default abstract methods.
  • Any variable should be final and static.
  • It is not instansable i.e Interface doesn’t have any constructor.
  • Example : List Interface _https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

package com.me.pack;

public interface SampleInterface {

static final int value=1;
abstract void method1(int a);
String method2();
}

  • If you wants to implement the interface then you should implement all its methods as below.

package com.me.pack;package com.me.pack;
public interface SampleInterface { static final int num = 10; static final String name = “John”;
abstract void method1(int a);
String method2();}
class SampleClass implements SampleInterface {
@Override public void method1(int a) { // TODO Auto-generated method stub System.out.println(SampleClass.num * a); }
@Override public String method2() { // TODO Auto-generated method stub return SampleClass.name; }
}

Why we need default method ?

Suppose if there is a Bank(I) which provides facilities to their customers by two ways i.e Customerservice(C)/Netbanking(C).Due to advancement bank about to provide a new way to reach out their customers through mobile banking then Then remaining two implemtors i.e Customerservice and Netbanking has to implement(avail) the new features so again we have to do lots code change.

Similarly default static method will works as a helper method.

Example:


package com.me.pack;

public class DefaultMethodsJava8 {
public static void main(String[] args) {

}
}

interface Bank {
default void mobileBanking() {
System.out.println(“Most people will do -1”);
}

default void virtualBanking() {
System.out.println(“less people will do -2”);
}

void customerService();

void netBanking();
}

interface Insurance {
static int getTheValue() {
return 123;
}

default void virtualBanking() {
System.out.println(“less people will do -2”);
}

void customerService();

void netBanking();
}

class HDFCBank implements Bank {

@Override
public void customerService() {
// TODO Auto-generated method stub
}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

}

class LibertyInsureur implements Insurance {

@Override
public void customerService() {
// TODO Auto-generated method stub

}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

}

class CombinerClass implements Insurance, Bank {

@Override
public void customerService() {
// TODO Auto-generated method stub

}

@Override
public void netBanking() {
// TODO Auto-generated method stub

}

// Has to implement this method
@Override
public void virtualBanking() {
// TODO Auto-generated method stub
Insurance.super.virtualBanking();
}

}


public class DefaultMethodsJava8 {
public static void main(String[] args) {
HDFCBank hdfcBank=new HDFCBank();
hdfcBank.customerService();
hdfcBank.netBanking();

//Any new implementaions can place here
hdfcBank.virtualBanking();
hdfcBank.mobileBanking();

Insurance insurance=new LibertyInsureur();
insurance.customerService();
insurance.netBanking();

//new features
insurance.virtualBanking();
//helper method
((LibertyInsureur) insurance).getHere();
Insurance.getTheValue();

CombinerClass combinerClass=new CombinerClass();
//Common has to implemt
combinerClass.virtualBanking();
}
}

 

Hidden features of JAVA-7

Here are some stuff  that I came across so far.

 1.NumberFormatException
int value = 123_8934758;
System.out.println(value);

2.String as argument in Switch condition.

String key1 = "HYD", key2 = "BLR";

Scanner scanner = new Scanner(new InputStreamReader(System.in));
String input = scanner.nextLine();

switch (input) {
case key1:
System.out.println("HYD HERE");
break;
case key1:
System.out.println("BLR HERE");
break;

default:
System.out.println("DEFAULT HERE");
break;
}

3. Diamond operator
When we doesn’t place both sides then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we doesn’t place at left side then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we place both sides then no issues and it accepts only specified Generic type.

When we place at left side then issues and it accepts only specified any type.

List list = new ArrayList();
List list2 = new ArrayList();
List list3 = new ArrayList();
List list4 = new ArrayList();

List list5 = new ArrayList();
List list6 = new ArrayList();

list5.add(new Long(123));
list5.add(new Integer(548));

list.add("ABC");
list.add(new Object());
list.add(new String("Hey"));
list.add(new Integer(125));

list2.add(new Object());
list2.add(new String("Hey"));
list2.add(new Integer(125));

list3.add(new Object());
list3.add(new String("Hey"));
list3.add(new Integer(125));

list4.add(new Object());
list4.add(new String("Hey"));
list4.add(new Integer(125));

4. Parallel catching of Exceptions:

When all are placed in different exception hierarchies then we can place as this.
NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex

If they fall under same hierarchy then use the base Exception. The below will gives you the CE.

catch (NullPointerException | IOException | ArithmeticException | FileNotFoundException ex) {
ex.printStackTrace();
}

If you are using Checked Exception then it should be thrown.
IOException etc.

try {
File file = new File("C://Demos//me.txt");
FileInputStream fileInputStream = new FileInputStream(file);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.readLine() != null) {
System.out.println(new SimpleDateFormat("DD/MM/YYYY"));
}
throw new ArithmeticException();
} catch (NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex) {
ex.printStackTrace();
}

5. Try with resource
Internally it uses implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println(“hey java-7 closable”);
}

try (BufferedReader bufferedReader = new BufferedReader(
new FileReader("C:\\Users\\n0290635\\Desktop\\het.txt"))) {
while (bufferedReader.readLine() != null) {
System.out.println(bufferedReader.readLine());
}
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}

try (CustomClass customClass = new CustomClass()) {
customClass.methodNene(123);
} catch (Exception exception) {
exception.printStackTrace();
}

class CustomClass implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println("hey java-7 closable");
}

public void methodNene(int a) {
System.out.println("result:" + a * a * 120);
}

}

6. Rethrow error -Throwing the exception in catch block too.
private static void rethrowErrorJAVA7() throws IOException, Exception {

try {
new SimpleDateFormat("yyyyMMdd").parse("foo");
new FileReader("file.txt").read();
} catch (ArithmeticException arithmeticException) {

} catch (Exception exception) {
throw exception;
}
}

Types of layouts in Log4j

There are numerous Layouts in log4j.

Refer Here : https://logging.apache.org/log4j/2.0/manual/layouts.html

Sample log4j.properties

# Root logger option
log4j.rootLogger=TRACE,stdout,file,filehtml,filexml,filejson
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n - %t - %r -%M
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=V:/logs/user_timings.log
log4j.appender.file.MaxFileSize=10KB
log4j.appender.file.MaxBackupIndex=3
log4j.appender.file.layout= org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%
# Redirect log messages to a log file, support file rolling.
log4j.appender.filehtml=org.apache.log4j.RollingFileAppender
log4j.appender.filehtml.File=V:/logs/user_timings_html.html
log4j.appender.filehtml.MaxFileSize=10KB
log4j.appender.filehtml.MaxBackupIndex=3
log4j.appender.filehtml.layout= org.apache.log4j.HTMLLayout
log4j.appender.filehtml.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.filexml=org.apache.log4j.RollingFileAppender
log4j.appender.filexml.File=V:/logs/user_timings_xml.xml
log4j.appender.filexml.MaxFileSize=10KB
log4j.appender.filexml.MaxBackupIndex=3
log4j.appender.filexml.layout= org.apache.log4j.xml.XMLLayout
log4j.appender.filexml.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.filejson=org.apache.log4j.RollingFileAppender
log4j.appender.filejson.File=V:/logs/user_timings_json.json
log4j.appender.filejson.MaxFileSize=10KB
log4j.appender.filejson.MaxBackupIndex=3
log4j.appender.filejson.layout= org.apache.log4j.xml.JSONLayout
log4j.appender.filejson.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 

output:

Untitled.png