Showing posts with label corejava. Show all posts
Showing posts with label corejava. Show all posts

August 23, 2021

Sort with given object multiple properties names, age using JAVA8

List can be sorted using Java 8 Lambda Expressions, moving right past syntactic sugar and into real and powerful functional semantics. The implementation of all of these examples and code snippets can be found over on gitHub: https://github.com/ramanujadasu/tutorials/tree/master/core-java-modules/core-java-lambdas

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 10), 
      new Human("Jack", 12)
    );


Basic Sort Without Lambdas:

    Collections.sort(humans, new Comparator<Human>() {
        @Override
        public int compare(Human h1, Human h2) {
            return h1.getName().compareTo(h2.getName());
        }
    });


Basic Sort With Lambda Support:

    humans.sort(
      (Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));


Basic Sorting With No Type Definitions:

	humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));

Sort Using Reference to Static Method:

public static int compareByNameThenAge(Human lhs, Human rhs) {
    if (lhs.name.equals(rhs.name)) {
        return Integer.compare(lhs.age, rhs.age);
    } else {
        return lhs.name.compareTo(rhs.name);
    }
}

humans.sort(Human::compareByNameThenAge);

Sort Extracted Comparators:

Collections.sort(
      humans, Comparator.comparing(Human::getName));

Reverse Sort:

Comparator<Human> comparator
      = (h1, h2) -> h1.getName().compareTo(h2.getName());
    
    humans.sort(comparator.reversed());


Sort With Multiple Conditions:

List<Human> humans = Lists.newArrayList(
      new Human("Sarah", 12), 
      new Human("Sarah", 10), 
      new Human("Zack", 12)
    );
    
    humans.sort((lhs, rhs) -> {
        if (lhs.getName().equals(rhs.getName())) {
            return Integer.compare(lhs.getAge(), rhs.getAge());
        } else {
            return lhs.getName().compareTo(rhs.getName());
        }
    });

Sort With Multiple Conditions -Composition:

humans.sort(
      Comparator.comparing(Human::getName).thenComparing(Human::getAge)
    );

Sorting a List With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");
	
List<String> sortedLetters = letters.stream().sorted().collect(Collectors.toList());
==
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
	
    	List<Human> sortedHumans = 
	      humans.stream().sorted(nameComparator).collect(Collectors.toList());

Or
  	List<Human> sortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName))
      	.collect(Collectors.toList());


Sorting a List in Reverse With Stream.sorted():

List<String> letters = Lists.newArrayList("B", "A", "C");

    List<String> reverseSortedLetters = letters.stream()
      .sorted(Comparator.reverseOrder())
      .collect(Collectors.toList());
==
 List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
    
	Comparator<Human> reverseNameComparator = 
      	(h1, h2) -> h2.getName().compareTo(h1.getName());

    	List<Human> reverseSortedHumans = humans.stream().sorted(reverseNameComparator)
    	 .collect(Collectors.toList());

Or
	List<Human> reverseSortedHumans = humans.stream()
      	.sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder()))
     	 .collect(Collectors.toList());

Null Values:
  List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12));

    humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
==
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12), null);

    humans.sort((h1, h2) -> {
        if (h1 == null) {
            return h2 == null ? 0 : 1;
        }
        else if (h2 == null) {
            return -1;
        }
        return h1.getName().compareTo(h2.getName());
    });

Or	
   humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName)));
Or
   humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName)));

Reference:
https://www.baeldung.com/java-8-sort-lambda

Read more ...

Custom Marker Interface Implementation in Java

Marker interface has no method. Java has built-in marker interface like Serializable, Cloneable & Event Listener etc that are understand by JVM.

We can create our own marker interface, but it has nothing to do with JVM, we can add some checks with instanceOf.


Create the empty interface

interface Marker{    }

Write a class and implements the interface 

class A implements Marker {
  //do some task
}

Main class to check the marker interface instanceof 

class Main {
    public static void main(String[] args) {
        A ob = new A(){
        if (ob instanceof A) {
            // do some task
        }
    }
}

Reference: 
https://stackoverflow.com/questions/11008033/how-to-write-our-own-marker-interface-in-java/35278304 
https://en.wikipedia.org/wiki/Marker_interface_pattern
Read more ...

Can we use return statement in finally block in java?

Bellow program output is always 2, as we are returning 2 from the finally block. Remember the finally always executes whether there is a exception or not. So when the finally block runs it will override the return value of others. Writing return statements in finally block is not required, in fact you should not write it.

 
public class Test {
    public static int test(int i) {
        try {
            if (i == 0)
                throw new Exception();
            return 0;
        } catch (Exception e) {
            return 1;
        } finally {
            return 2;
        }
    }

    public static void main(String[] args) {
        System.out.println(test(0));
        System.out.println(test(1));
    }
}

Output:
2
2

Reference: 
https://stackoverflow.com/questions/18205493/can-we-use-return-in-finally-block

Read more ...

August 10, 2018

Given strings are Anagram or not?

Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
check-whether-two-strings-are-anagram-of-each-otherWe strongly recommend that you click here and practice it, before moving on to the solution.


Program:
public class Anagram {
public static void main(String[] args) {
String input1 = "d1asu";
String input2 = "adsu";
System.out.println("Given string are input1: " + input1 + ", input2: " + input2);
System.out.println("" + isAnagram(input1, input2));
}
private static String isAnagram(String input1, String input2) {
String result = "Given strings are not anagram";
boolean isAnagram = false;
if (!input1.isEmpty() && !input2.isEmpty() && (input1.length() == input2.length())) {
char[] arr = input1.toCharArray();
StringBuilder sb = new StringBuilder(input2);
for (char a : arr) {
int index = sb.indexOf("" + a);
if (index != -1) {
sb.deleteCharAt(sb.indexOf("" + a));
}
}
isAnagram = sb.toString().isEmpty();
}
if (!isAnagram) {
return result;
}
return "Given strings is anagram";
}
}
Output:
Given string are input1: d1asu, input2: adsu
Given strings are not anagram
Reference:
https://www.devglan.com/java-programs/anagram-test
https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/


Read more ...

Given String is Pangram or not?


Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.
Examples : The quick brown fox jumps over the lazy dog ” is a Pangram [Contains all the characters from ‘a’ to ‘z’]
“The quick brown fox jumps over the dog” is not a Pangram [Doesn’t contains all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
We create a mark[] array of Boolean type. We iterate through all the characters of our string and whenever we see a character we mark it. Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25.
After iterating through all the characters we check whether all the characters are marked or not. If not then return false as this is not a pangram else return true.

Program:

public class Panagram {


public static void main(String[] args) {
String input = "The quick brown fox jumps over the lazy dog";
System.out.println("Panagram test string : "+input);

System.out.println(""+ checkPanagram(input));
}

/**
*Returns true if the string     is pangram else false
* @param input
* @return
*/
private static String checkPanagram(String input) {
String result = "Given string is not panagram";
  // Create a hash table to mark the
        // characters present in the string
        // By default all the elements of
        // mark would be false.
boolean[] mark = new boolean[26];

if(input == null) {
return "Given input is invalid";
}
// For indexing in mark[]
int index = 0;
// Traverse all characters
for(int i=0;i // If uppercase character, subtract 'A'
            // to find index.
if( 'A' <= input.charAt(i) && input.charAt(i)  <= 'Z') {
index = input.charAt(i) - 'A';
System.out.println("current value: "+input.charAt(i)+", index :"+index);
}
// If lowercase character, subtract 'a'
            // to find index.
if( 'a' <= input.charAt(i) && input.charAt(i)  <= 'z') {
index = input.charAt(i) - 'a';
System.out.println("current value: "+input.charAt(i)+", index :"+index);
}
// Mark current character
mark[index] = true;

}
System.out.println("mark: "+mark+", length: "+mark.length);
// Return false if any character is unmarked
for(int j =0;j if(mark[j] == false) {
return result;
}
}
// If all characters were present
return "The Given String is panagram.";
}

}



Output:
Panagram test string : The quick brown fox jumps over the lazy dog
current value: T, index :19
current value: h, index :7
current value: e, index :4
current value: q, index :16
current value: u, index :20
current value: i, index :8
current value: c, index :2
current value: k, index :10
current value: b, index :1
current value: r, index :17
current value: o, index :14
current value: w, index :22
current value: n, index :13
current value: f, index :5
current value: o, index :14
current value: x, index :23
current value: j, index :9
current value: u, index :20
current value: m, index :12
current value: p, index :15
current value: s, index :18
current value: o, index :14
current value: v, index :21
current value: e, index :4
current value: r, index :17
current value: t, index :19
current value: h, index :7
current value: e, index :4
current value: l, index :11
current value: a, index :0
current value: z, index :25
current value: y, index :24
current value: d, index :3
current value: o, index :14
current value: g, index :6
mark: [Z@70dea4e, length: 26
The Given String is panagram.


References:
https://www.geeksforgeeks.org/pangram-checking/

Read more ...

July 23, 2018

JAVA9: JSHELL (jshell) tool will be a command-line tool

In this article we will discuss about jshell(Java Shell) Java 9 feature. We can explore jShell with JDK 9 Early Access Release.  As of now the general availability of JDK9 is scheduled to 27th July, 2017. The jShell feature is proposed as part of JEP 222. The motivation behind jshell is to provide interactive command line tools to explore the features of java quickly. It is very useful tool to get the glimpse of Java features very quickly for the new learners. Already Java is incorporating functional programming features from Scala. In the same direction they want REPL(Read-Eval-Print Loop) interactive shell for Java as Scala, Ruby, JavaScript, Haskell, Clojure, and Python.

                       The jshell tool will be a command-line tool with features like, a history of statements with editing, tab completion, automatic addition of needed terminal semicolons, and configurable predefined imports.
After downloading the JDK 9, set the PATH variable to access jshell. Now, we will see how to use jshell. Below is the simple program using jshell. We no need to write a class with public static void main(String[] args) method to run simple hello world application.
C:\Users\ABC>jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell> System.out.println("Sayo to jshell!!!");
Say hello to jshell!!!

jshell>
Now we will write method which will add two variables and invoke method via jshell.
jshell> public class Sample {
   ...> public int add(int a, int b) {
   ...> return a+b;
   ...> }
   ...> }
|  created class Sample
jshell> Sample s = new Sample();
s ==> Sample@49993335

jshell> s.add(10,9);
$4 ==> 19
jshell>
Now, we will create a static method with StringBuilder class without importing it, as jshell does that for you.
jshell> public class Sample {
   ...> public static void join() {
   ...> StringBuilder sb = new StringBuilder();
   ...> sb.append("Smart").append(" ").append("Techie");
   ...> System.out.println("Theng is " + sb.toString());
   ...> }
   ...> }
|  created class Sample

jshell> Sample.join();
The string is Smart Techie

jshell>


Read more ...

November 11, 2017

Difference between SLF4J and LOG4J

SLF4J is basically an abstraction layer. It is not a logging implementation. It means that if you're writing a library and you use SLF4J, you can give that library to someone else to use and they can choose which logging implementation to use with SLF4J e.g. log4j or the Java logging API. It helps prevent projects from being dependent on lots of logging APIs just because they use libraries that are dependent on them.
So, to summarise: SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your library/app.
Take a look here: http://www.slf4j.org/, or even here: http://commons.apache.org/logging/ (Apache Commons Logging is similar to SLF4J) for more info on this concept.

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.

If you using SLF4J along with Log4j, if required Log4j can be swapped with another logging framework like Logback without compiling the source code. Logback is the reference implementation for SLF4J.
Read more ...

My Favorite Site's List

#update below script more than 500 posts