الجمعة، 31 مايو 2019

Java String API replace() Method Example

1. Java String replace() Overview


In tutorial, We'll learn about Java String replace() method and explanation with examples. replace() method is used to replace a character with another character in a String and this method returns a new string after replacing characters.

In previous tutorial, We've seen How to use Java 11 String API repeat() method.

Java String API replace() Method Example

1.1 Syntax


public String replace​(char oldChar, char newChar)
public String replace​(CharSequence target, CharSequence replacement)

replace() method is available in two variants. First variant takes two char's as input and replace a char by a new char. Where as in second variant, It takes two CharSequence as arguments and replace one CharSequence by new CharSequence.

Here, CharSequence means String, StringBuffer, StringBuilder. Any one of these can be passed as arguments to the second variant of replace().

الأربعاء، 29 مايو 2019

Java 11 String API repeat​() Method Example

1. Java 11 String repeat​() Method Overview


In this tutorial, We'll learn about Java String API repeat​() Method with examples. repeat() method repeat​s the string given n number of times.

repeat() method works as it name suggests.

Java 11 String API repeat​() Method Example

1.1 Syntax

public String repeat​(int count)

This is a public method and can be accessed on string instance directly.

1.2 Parameters

count - number of times to repeat

If we pass count as 3 then string repeats 3 times.

الثلاثاء، 28 مايو 2019

Java String API matches​() Method Example

1. Java String API matches​(String regex) Overview

In this tutorial, We'll learn about Java String API matches​() Method with Example programs. And also will explain how this method works internally.

matches() method tells whether or not this string matches the given regular expression.

In simple words, First regular expression is a pattern which tells string should have only alphabetic's or numbers. This pattern can be anything or specified character set.

If the string fits into the specified regular expression pattern then matches() method returns true. Otherwise returns false.



Java String API matches​() Method Example

Java String API length() Method Example

1. Java String length() Overview

In this tutorial, We'll learn how to find the length of the String using Java String API Length() Method. In other words, Counting the number of characters in String.

Knowing the string length is very important in iterating the string.

Note: All the blank spaces in string are counted as character.

Java String API length() Method Example

Java 11 String API isBlank() Method Example

1. isBlank Method Overview

In this tutorial, We'll learn about new java 11 string isBlank() method and explanation with examples. And also how to check the string is blank or not using isBlank() method.

This method is introduced in Java 11.
Read complete article on What is new in Java 11 String API.

Java 11 String API isBlank() Method Example

Java String intern() Method Example

1. Overview

In this post, We'll learn String intern() method in java with examples and This is part of java.lang package. Intern method is invoked automatically on every string literal creation.

String is immutable that means a new String object will be created for every operation or invoking any method on string object. In another words, Original String content will not be modified.


Java String intern() Method Example



الاثنين، 27 مايو 2019

Java String indexOf() Method Example

1. Overview

In this tutorial, We will learn about String indexOf() method with example on how to check whether the specified character is present in the input string or not.

Java String indexOf() Method Example

Java 12 String API indent​() Method Example

1. Overview

In this quick tutorial, We'll learn new indent() introduced in JDK 12 in Java.lang.String class.

Demonstrated with examples how to use indent() method.

Please read article on Java 12 new String API methods addition.


Will go through its internal code and how it works.

Java 12 String indent​() Method Example

Java String getChars()​ Method Example

1. Overview

In this quick tutorial, We'll learn about String getChars​ method with examples. As well will take a look at internally how getChars​ method implemented and works.

Java String getChars​ Method Example


2. getChars​

This method copies the characters from this string into the destination character array. Also getChars​() method copies only a specified range of characters into new char array.
Source String start index, end index and destination array start index can be configured.

Removing All Duplicate Values from ArrayList including Java 8 Streams

1. Overview

In this tutorial, We'll learn how to clean up the duplicate elements from ArrayList. Many of the scenarios we do encounter the same in real time projects. But, this can be resolved in many ways.

We will start with Set first then next using new List with using built in method contains() before adding each value to newList.

Next, will see duplicate elements removal with new java 8 concept Streams.

Then later, interestingly we have a list with Employee objects. Employee has id and name. Some Employee objects are added to list. Later realized that list has now duplicate employee based on the id. Now how to remove custom duplicate objects from ArrayList.

Removing All Duplicate Values from ArrayList including Java 8 Streams

الجمعة، 24 مايو 2019

Fix to Invalid byte tag in constant pool: 15 in Tomcat 7+ Java 8

1. Overview

ClassFormatException: Invalid byte tag in constant pool: 15 solution:
I was working with java version 1.7 and Apache Tomcat/7.0.12.. I have updated java version to 1.8(C:\Program Files\Java\jdk1.8.0_51)

I was eagerly waiting to work with java 8 features. I just restarted my tomcat server.. then given stack trace below exception.




Invalid byte tag in constant pool 15

Iterate Map in Java 8 Steam API (Lamda Expression) and Older JDK

1. Overview

In this tutorial, We'll learn How to Iterate Map and How to Iteration HashMap in Java using various ways.

Iterating is very common process in any programming language using very basic for loop.

There are 6 different ways to extract or loop over Map in java such as using enhanced for loop, Iterator using EntrySet, Java 8 and stream API.

Most exciting is about lambda part and most of the projects are already migrated to Java 8 but may not be using full features of Java 8.

Iterate Map or HashMap in Java.PNG


As all of us know, ArrayList is directly iterated using Iterator but it is not possible encase of Map because Map is not under Collection interface.


We must know about internals of how hashmap works in java. HashMap creates internally Hashset and added Entry objects into Hashset.

Map.Entry object looks like below.

   static class Node implements Map.Entry {
   final int hash;
   final K key;
   V value;
   Node next;

  // constructor, setters and getters

  }

In all examples today will be executed on the below input. All these values are stored in set in the form of Node<String, String> which is an Map.Entry object.

Map hashMap = new HashMap<>();
hashMap.put("Map", "HashMap");
hashMap.put("Set", "Hashset");
hashMap.put("List", "ArrayList");

2. Map.entrySet() using for each


Map has a method entryset() which returns the Set object. In our case, it is Set<Entry<String, String>> and this holds Entry<String, String> objects.

Now we will iterate through enhanced for loop this set. See the code below.


for (Map.Entry entry : hashMap.entrySet())
 System.out.println("Key(Interface) = " + entry.getKey() + ", Value(Implementation class) = " + entry.getValue());
}

First, retrieving the each object from set in the form of entry object and then next calling getKey() to get the key from Node/Entry object and getValue() method to get the value of the corresponding key.

Output:

Key(Interface) = Set, Value(Implementation class) = Hashset
Key(Interface) = List, Value(Implementation class) = ArrayList
Key(Interface) = Map, Value(Implementation class) = HashMap

This methodology is commonly used by all programmers if want to retrieve both key and value at the same time.

3. keySet() and values() methods

We might need to get the only keys some scenario where values are not required and vice versa. In these type of situations, we'll try to minimize getting entire key-value pair. Map has provided methods to get only keys or values by invoking methods keyset() and values().


// Retrieving only keys
for (String interfaceName : hashMap.keySet()) {
 System.out.println("Key(Interface): " + interfaceName);
}

// Retrieving only values
for (String ImplementationClassName : hashMap.values()) {
 System.out.println("Value(Implementation class): " + ImplementationClassName);
}

Output:

Key(Interface): Set
Key(Interface): List
Key(Interface): Map
Value(Implementation class): Hashset
Value(Implementation class): ArrayList
Value(Implementation class): HashMap

4. entrySet().iterator()

Next approach is as Similar to Section 2, Here as well first need to call the entrySet() method which returns set.
Now we have set object and set has a method iterate().

See the below code.

Set> entrySet = hashMap.entrySet();
Iterator> iterator = entrySet.iterator();

while (iterator.hasNext()) {
 Entry entry = iterator.next();
 System.out.println(
   "Key(Interface) = " + entry.getKey() + ", Value(Implementation class) = " + entry.getValue());
}

We'll now iterate tradition mechanism using hasNext() and next() methods.

hasNext(): returns true if next element is present in the collection. Otherwise false.
next(): returns next object from collection.

Output will same as in section 2.

5. Lamda Expression - forEach()


Java 8 introduced Lamda concept which is in funcitonal programming. Lamda's reduces code to very minimal to our core logic and remaing take care by Lamda.

Now take a look at the below code using Map.forEach() method. forEach method takes BiConsumer as argument and calls it's accept() method.

hashMap.forEach((k, v) -> System.out.println("Key(Interface) = " + k + ", Value(Implementation class) = " + v));

All of this logic now bacame to single line. This is the power of lambda.

(k, v) is passed to the accept() method and adds System.out.println() inside method body as below.


accept(String k, String v){
 System.out.println("Key(Interface) = " + k + ", Value(Implementation class) = " + v)
}

Output will be same as section 2.

Look at interesting article on "Iterating String Array Examples"

6. Stream API

Stream api also introduced in Java 8 and most powerful rich feature. Stream api primarly designed for collection api and provides the way to process collection sequentially and parellel.

Iterating map using Stream api
is simple. But streams are extremly useful when we do aggregation operations.

First invoke entrySet().stream() method which inturn returns Stream object.

Stream> entriesStream = hashMap.entrySet().stream();

Next, Stream intreface has void forEach(Consumer<? super T> action) method. This forEach method iterates the Entry objects that are in the entrySet(). See the below code.

entriesStream.forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));

Output:

Set - Hashset
List - ArrayList
Map - HashMap

We can still further rewrite the above code into single line as below which will produce the same output.

hashMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));

7. Get Key and Search for it's value

As of now, we get both key and value at the same time in all above methods discussed as of now. But there is a way to get keys first and iterate keys to get value for each key by calling map.get(key) method.

for (String key : hashMap.keySet()) {
 String value = hashMap.get(key);
 System.out.println(key + " - " + value);
}

This code works fine and generate the expected output but this code is not efficient to run through huge key-value pair maps.

This solutin is not suggested and caught error complaining stating "WMI_WRONG_MAP_ITERATOR" in FingBugs because doing loop up for each key in map again calling get() method.
Use any one of above methods that will solve this problem.

8. Conclusion


In this tutoril, We've seen all possible ways on how to iterate through a map in java including java 8 stream concpets.

Further more covered Stream api forEach and map forEach methods with examples and inefficient way of iterating map which is not suggested by FindBugs.

All codes shown in this tutorail are available on GitHub.

الخميس، 23 مايو 2019

Find Unique and Duplicates Values From Two Lists

1. Overview

In this tutorial, We'll learn how to find the unique values from two lists and how to find all common or duplicates values from two lists.

We'll demonstrate using two ArrayList's to find out unique and duplicates objects in it.

To achieve our requirement, we must compare values in both list. Either we can run the loop through each list or we can use list api built in methods. We'll explore using built in api methods such as contains(), retailAll() and removeAll() methods.




Find Unique and Duplicates From Two Lists

الأربعاء، 22 مايو 2019

How To Print 1 to 100 Numbers Without Using Any Loop statements

1. Overview

this tutorial, We'll learn how to print 1 to 100 without using loop statements.

Couple of year back, My friend was asked this question in interview. He has given many tries but finally he could give the answer using recursive approach. This interview question will be asked to check how we understand the concepts and how we are using it on problem.

Print 1 to 100 Numbers Without Using Any Loop statements
Actually this can be done using any loop statements such as For Loop or While Loop. But, we'll see using normal and recursive approach.

2. Normal Approach


In the normal approach, printing numbers from 1 to 100 is done by for or while loop running from pointer 1 to 100.

2.1 for loop

A comprehensive guide to For Loop with Examples.


for (int i = 1; i <= 100; i++) {
 System.out.println(i);
}

2.2 While loop

A comprehensive guide to While Loop with Examples.

int j = 1;
while (j <= 100) {
 System.out.println(j);
 j++;
}

3. Recursive Approach

Recursion: A method calls itself again and again to resolve a problem that is until a given condition is met.

We will implement in Java, C++ and Python programming languages.
Here recursive approach starts from number 100 to 1 because it creates a stack for each self call. First call for 100 will be placed in the stack and 99 next ... and so on.. for 1 st num method call be on top of stack. Once seeing the program, you will be getting clear idea.

3.1 Java


public void printNnumber(int toNumber) {
 if (toNumber > 0) {
  printNnumber(toNumber - 1);
  System.out.print(toNumber + " ");
 }
 return;
}

3.2 C++


public: 
void printNnumber(unsigned int toNumber) 
{ 
    if(toNumber > 0) 
    { 
        printNnumber(toNumber - 1); 
        cout << toNumber << " "; 
    } 
    return; 
} 
}; 

3.3 Python

indentation is important in Python.

def printNnumber(toNumber): 
    if toNumber > 0: 
        printNnumber(toNumber - 1) 
        print(toNumber, end = ' ') 

4. Output

Output for all programs above should be same. We have tested all these programs in latest versions.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 

5. Conclusion

In this tutorial, we've seen printing the numbers from 1 to any without using loop.

Further article, implementation is done in java, c++ and python 3.

The same logic can be used on any pattern such print your name 100 times without using for loop or print pattern without loop, print number series etc.

All codes are shown here are available on GitHub.

الثلاثاء، 21 مايو 2019

Tomcat 7+ Java 8 : Invalid byte tag in constant pool: 15 and invalid byte tag in constant pool 19

1. Overview

ClassFormatException: Invalid byte tag in constant pool: 15, 18, 19 solution:
I was working with java version 1.7 and Apache Tomcat/7.0.12.. I have updated java version to 1.8(C:\Program Files\Java\jdk1.8.0_51)

I was eagerly waiting to work with java 8 features. I just restarted my tomcat server.. then given stack trace below exception.



Invalid byte tag in constant pool 15

2. Exeception occurred after Tomcat 7 restart:

Aug 22, 2015 10:57:05 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15
    at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:131)
    at org.apache.tomcat.util.bcel.classfile.ConstantPool.(ConstantPool.java:60)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1917)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1806)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1765)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1751)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1255)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:882)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:317)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:89)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5081)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:620)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:431)

I have surprised.. what was this new problem never encountered. checked tomcat official website. Stated that "The "offical answer" is that Tomcat 7 runs on Java 8, see http://tomcat.apache.org/whichversion.html("Java version 6 and later")."

3. Solution 1 :

However, if annotation scanning is enabled (metadata-complete="true" in web.xml) there are some issues due to BCEL (not able to process the new Java 8 byte codes). You will get exceptions like (at least with Tomcat 7):

SEVERE: Unable to process Jar entry [jdk/nashorn/internal/objects/NativeString.class] from Jar [jar:file:/usr/lib/jvm/jdk1.8.0_5/jre/lib/ext/nashorn.jar!/] for annotations

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15
    at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:131)
If not using annotation scanning, everything works fine, starting release 7.0.53 (updated compiler with better Java 8 support).

(UPDATE 2014-10-17) If your are using annotation scanning and your own code is not Java 8 based, another solution is to add the following line in /etc/tomcat7/catalina.properties (text added after "ant-launcher.jar" so part of property tomcat.util.scan.DefaultJarScanner.jarsToSkip):


junit.jar,junit-*.jar,ant-launcher.jar,\

jfxrt.jar,nashorn.jar
Tested with Tomcat 7.0.28 and Oracle JDK 8_25 on Debian 7.6.


4. Solution 2 :

Upgrade the tomcat version to Tomcat 7.0.65. Works well.


Solution 2 is simple, definitely works.

There are some more scenarios which causes the same problem which is below case and another case as well. We have provided other alternative solutions based many user experiences. Hope helps.

4.1 Problem: Tomcat 7 - Servlet 3.0: Invalid byte tag in constant pool:

I just switched the web.xml to servlet 3.0 (from a app running 2.4 previously) and now I'm seeing the following error (turned on fine logging for org.apache.tomcat.util):

Following is the problem requirements.

tomcat 7.0.16
Java 1.6.0_22
CentOS 5.6

4.2 Error occurred for ClassFormatException:



mtyson  FINE: Scanning JAR [file:/usr/java/jdk1.6.0_22/jre/lib/ext/jcharset.jar] from classpath
mtyson  Jul 19, 2011 10:04:40 AM org.apache.catalina.startup.HostConfig deployDirectory
mtyson  SEVERE: Error deploying web application directory ROOT
mtyson  org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 60


5. Solution 3:

It may not be your issue, but mine was the same as this one -- an old version of com.ibm.icu:icu4j. I solved the problem by changing by build configuration to exclude the older transitive dependencies and explicitly depending upon the latest version (4.8).

6. Solution 4:

Adding a attribute in the web application web.xml file to your web.xml should sort the issue (metadata-complete="true")

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

         metadata-complete="true">

7. Solution 5:

I was facing the same issue from a week and resolved by simply replacing the icu4j.2.1.jar file with latest version of jar.


8. Conclusion


In this tutorial, We've seen in which scenario's ClassFormatException while working with tomcat + Java 8.
In further in this article, discussed most useful 5 solutions to solve this issue.
That's all.

الأحد، 19 مايو 2019

Java Fix to Syntax error on token “;”, { expected after this token

1. Overview


In this tutorial, We'll learn how to fix "Syntax error on token “;”, { expected after this token" compile time error in Java.

This is very common error while writing java programs for beginners.



Syntax error on token “;”, { expected after this token


We'll explore how to solve these kind of compile time errors now.

الخميس، 16 مايو 2019

6 Solutions To Fix ‘Antimalware Service Executable’ High CPU Usage

1. Introduction

In this tutorial, we'll learn how to fix high cpu usage caused by antimalware service executable and also we put together a few simple steps you can follow to prevent Antimalware Service Executable from hogging your system’s resources and keep your machine running smoothly without malware.

The Antimalware Service Executable process plays an important role in the Windows Defender Service that comes bundled with Windows 10. However, it’s also infamous for consuming far more than its fair share of CPU processing power, and can even single handed to reduce your computer’s speed to a glacial crawl.

What is Antimalware Service Executable? Why is it consuming high CPU/Memory?



How to fix ‘Antimalware Service Executable’ high CPU usage | 5 Best Ways Explained


If you’re a Windows Defender user and have noticed high CPU usage for abnormally long periods of time, you’ll be pleased to know that the issue can easily be resolved.

الثلاثاء، 14 مايو 2019

Insert a String into another String in Java

1. Overview

We'll demonstrate how to add a string into another string at any given position in java.

We will write implementation in 3 ways which iterate through the string till given position and then add new string, finally add the remaining original string.

As we know String class is immutable in java. Any operation on string will result a new String.

Insert a String into another String

الاثنين، 13 مايو 2019

Guide To Check Char Is In String In Java - indexOf(), lastIndexOf​()

1. Overview

In this tutorial, We will check the possible ways to check the given char or string in the given string. If the char is present then need to return it's index.

Throughout this post, we will be writing the examples on below string.

Check Char Is In String

String string = "find string";


indexof() and lastIndexOf methods return int value as index of the found character.

Please go through the previous post, how String contains() method works in java with examples. This post will give you understanding how indexof method is used internally.

السبت، 11 مايو 2019

How To Remove a Character in String in Different Ways

1. Overview

In this tutorial,  We'll explore how to remove a character from a String. Need to remove only one character even though it is at any position or appears several times.
String class has many utility methods that are very useful when working with Strings such as isEmpty(), equals(), contains() and many.

Guide to Remove a Character in String


For accessing a character at a specified position, String class has a charAt method. But String api is not having any method to remove a char from String. So, How do we remove from String. We will see different ways to do it. But remember, String is immutable that means once string is created it's content can not be changed. A new string object will be created for every operation done on it.

We will be using string "Jhonny Jhonny Yes Papa" in all our examples in this post.

String string = "Jhonny Jhonny Yes Papa";


2. replace()

Replace() method takes two parameters i.e. oldChar - the old character and newChar - the new character.
This method does replace all the occurrences of oldChar with newChar . To remove a character from String, we have to replace the old character with empty space "".

2.1 Example

We are going to replace now char n with "" emtpy space that means removing "n" from input string. See the below example code.

String newString = string.replace("n", "");

2.2 Output

See the output after removing char 'n' and replaced with empty space.

newString : Jhoy Jhoy Yes Papa

2.3 Removing all spaces

Removing all spaces from string using replace method. We need to pass oldChar as " " and newChar as "".

String removeAllSpaces = string.replace(" ", "");

2.4 Output

Observe the output and it has removed all spaces.

removeAllSpaces: JhonnyJhonnyYesPapa

All occurances of "n" is removed from input string.

3. substring()

String class has another method substring(). This method returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

3.1 Example

We'll take out char 'o' from second index using substring method. substring method will take the string from startIndex to endIndex-1.
First take substring from index 0 to 2 and next substring from 3 to string.length. Now, we have to merge these two strings to get the final desired string with removing char 'o'.

String newSubString = string.substring(0, 2) + string.substring(3, string.length());

3.2 Output

newSubString: Jhnny Jhonny Yes Papa

4. StringBuilder

StringBuilder class is available from jdk 1.5 onwards and this is a mutable class that holds mutable sequence of characters. StringBuilder is not synchronized.

StringBuilder has a method deleteCharAt() to remove the character from a specified index.

4.1 Example

In the below example code, we will delete the character 'o' at index 2 (Index starts from 0). Just we need to pass the index to the deleteCharAt method.

StringBuilder builder = new StringBuilder("Jhonny Jhonny Yes Papa");
builder.deleteCharAt(2);
String builderString = builder.toString();

4.2 Output

Let us have a look at the output, first occurrence of char 'o' is deleted.

builderString: Jhnny Jhonny Yes Papa

4.3 Exception

We should deal deleteCharAt method very carefully. If index is more than string length then it will throw runtime exception saying "StringIndexOutOfBoundsException".

builder.deleteCharAt(200);

Here length of input string is 22 but passing 200 which is greter than it's length. So, It led to exception. See the below complete exception stack trace.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 200,length 22
 at java.base/java.lang.String.checkIndex(String.java:3369)
 at java.base/java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:916)
 at java.base/java.lang.StringBuilder.deleteCharAt(StringBuilder.java:293)
 at com.java.w3scools.blog.string.getbytes.CharRemovalFromString.main(CharRemovalFromString.java:11)

5. Regular Expression

Regular Expression are very important to reduce the developers work but it may reduce the peformance.

5.1 Example

String regexString = string.replaceFirst("(?s)(.{2}).(.*)", "$1$2");

Explanation:

"(?s)"   - tells regexp to handle newlines like normal characters (just in case).
"(.{2})" - group $1 collecting exactly 2 characters
"."      - any character at index 2 (to be squeezed out).
"(.*)"   - group $2 which collects the rest of the inputString.
"$1$2"   - putting group $1 and group $2 together.

5.2 Output

String after removing second index using regular expression.

regexString: Jhnny Jhonny Yes Papa

5.3 Remove Lowecase Letters

Using regular expression, we can remove all the lowercase letters from string.

String removeLowecase = string.replaceAll("([a-z])", "");

5.4 Output:

String after removing all lowercase letters from input string.

removeLowecase: J J Y P

6. Conclusion

In this article, We've discussed all possible ways to delete a character from String using replace(), StringBuilder, substring() and regular expression calling replaceFirst and replaceAll methods. But usage of regular expression is not suggested to use and recommended only if we could not achive using any other alternative peice of code.

All the programs are implemented using JDK 12 in this course.

As usual, all code are described in this tutorial are on GitHub.

الخميس، 9 مايو 2019

Java 12 String API Additions

1. Overview

Java 12 added a few useful APIs to the commonly used String class. In this tutorial, we will explore and use these new APIs.

  • indent​(int n)
  • transform​(Function<? super String,​? extends R> f)
  • describeConstable()
  • resolveConstantDesc​(MethodHandles.Lookup lookup)


Take a look at Java 11 String API methods which are discussed in depth in the last article.


In all our example, we will use String string = "Java-W3schools";

2. indent (int n)

As the name suggests, the indent () instance method provides the indentation for the given string that means it will add or remove the white characters at the beginning of the string.

Where method argument n indicates the number of leading white space characters to add or remove.

2.1 Signature

public String indent​(int n)

If n value is positive then adds leading white spaces.
If n value is negative then removes leading white spaces.
If n value is zero then the input string is unchanged.

2.2 Example - n positive

See the example program on indent method with value 5.

String value = "indent";
System.out.println(value);
System.out.println(value.indent(5));

2.3 Output

indent
     indent

See the difference between the original string and indented string. Indented string now has 5 empty spaces added to it.

2.4 Example - n negative


In this example, passing a negative value to it and added 4 empty spaces to the input string at the beginning.

String value = "    indent";
System.out.println(value);
System.out.println(value.indent(5));

2.5 Output

Now observe the output and it has removed 2 empty spaces at the beginning.

    indent
  indent

If the input string is not having empty spaces at the beginning if n is negative then it will not do anything. Simply it returns the same string.

2.6 Example - n is zero

String inputNZero = "welcome";
System.out.println(inputNZero.indent(0));

2.7 Output

welcome

2.8 Internal Code

Internally, first, it converts the input string into lines by calling line() method then it will add n empty spaces by calling " ".repeat(n). Finally, it appends the empty spaces to each line at the beginning.


public String indent(int n) {
        return isEmpty() ? "" :  indent(n, false);
    }

    private String indent(int n, boolean removeBlanks) {
        Stream stream = removeBlanks ? lines(Integer.MAX_VALUE, Integer.MAX_VALUE)
                                             : lines();
        if (n > 0) {
            final String spaces = " ".repeat(n);
            stream = stream.map(s -> spaces + s);
        } else if (n == Integer.MIN_VALUE) {
            stream = stream.map(s -> s.stripLeading());
        } else if (n < 0) {
            stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
        }
        return stream.collect(Collectors.joining("\n", "", "\n"));
    }


3. transform (Function<? super String, ? extends R> f)


Transform method is important and used to transform the string into one form to another form using Function Functional interface.

Must be used with lambda expression only because Function is part of Java 8 stream API.

3.1 Signature

public  R transform​(Function f)

3.2 Example


We will see a few scenarios in this example program now. If we want to convert all elements of List into uppercase or append some value to it, then the transform method is most usable.

  List fruits = new ArrayList<>();

  fruits.add("Mango");
  fruits.add("Apple");
  fruits.add("Banana");
  fruits.add("Avvacado");
  fruits.add("Papaya");

  List newFruitsList = fruits.stream().map(s -> s.transform(str -> str.toUpperCase())).collect(Collectors.toList());

  System.out.println(newFruitsList);


3.3 Output

From fruits list stream, taking one by one fruit name and passing to transform function which converts into uppercase by calling toUpperCase() method of String class. Collecting all outputs of transform() method into a List using Collectors.toList() method.

[MANGO, APPLE, BANANA, AVVACADO, PAPAYA]

Not only toUpperCase() method but also can be used any operation that can be performed on String either adding some content to it or anything. Now just adding "Halwa" to each string in the fruits list.

s -> s.transform(str -> str + " Halwa")

Now the newFruitsList will have the values with added " Halwa" string to each fruit name.

[Mango Halwa, Apple Halwa, Banana Halwa, Avvacado Halwa, Papaya Halwa]

3.4 Internal Code

Internally it just invokes the f.apply() method.

 public  R transform(Function f) {
        return f.apply(this);
    }

4. describeConstable()

Returns an Optional containing the nominal descriptor for this instance, which is the instance itself.

4.1 Signature

public Optional describeConstable()

Java 12 has introduced Constants API in JEP 334. If you look at the String class documentation, it implements two new interfaces from Constants API – Constable, and ConstantDesc. This method is declared in the Constable interface and implemented in the String class.

4.2 Example


 String status = "SUCCESS";
 Optional optional = status.describeConstable();
 System.out.println(optional);
 System.out.println(optional.get());
 System.out.println(optional.isPresent());

4.3 Output

Optional[SUCCESS]
SUCCESS
true

5. resolveConstantDesc (MethodHandles.Lookup lookup)

Resolves this instance as a ConstantDesc, the result of which is the instance itself.

5.1 Signature

public String resolveConstantDesc​(MethodHandles.Lookup lookup)

5.2 Example


 String string = "resolveConstantDesc​";
 String constDesc = string.resolveConstantDesc(MethodHandles.lookup());
 System.out.println(constDesc);

6. Conclusion

In this tutorial, We've seen the new methods added in Java 12 version. indent (...) and transform() methods add great value to String API. But describeConstable() and resolveConstantDesc methods are not much useful for developers when working on Strings.

Programs shown in this post are available on GitHub. All these programs are downloadable.


الأربعاء، 8 مايو 2019

Java 11 String API New Methods

1. Java 11 String API New Methods Overview:

Java 11 is a new updated version with lots of changes similar to java 8. Java is free to use in production environments till java 10. But, java 11 onwards we should get license to use production environments.

String is a collection of characters including alphabets, numeric, special characters and as well supports 256 bit character set (any character).
Java 11 String API

Java strings are constants that means once created, values of string can not be changed. This is called as Immutable. Immutable is to get the advantage sharing the objects in multi-threading.

Following are the new methods added in Java 11 java.lang.String class.

Java 11 - String API New Methods

1.1 Java 11 String API Additions:

1) isBlank()
2) lines()
3) repeat​(int count)
4) strip()
5) stripLeading()
6) stripTrailing()

الاثنين، 6 مايو 2019

A Guide to Apache Accumulo

1. Overview:

In this tutorial, We will learn about Apache Accumulo and its API to process the large data-set as part of Big Data ecosystem.

Apache Accumulo is designed based on Google's Bigtable which is written in java and built on top of Hadoop, ZooKeeper and Apache Thrift. This is the best choice after Cassendra and HBase in NoSQL column oriented data store. This is designed mainly for structure data storage and processing.

Accumulo provides very efficient storage model which is the best in retrieving the data.
It provides tables which can be accessed using query language to query the tables with optional conditions as well as these tables can be passed as input to map reduce jobs.



Download latest version of Accumulo from here

A Guide to Accumulo


2. Accumulo Design

Accumulo is designed based on the key/value pair which is very simple and straight forward for understanding. This is a very richer data model but not a fully relational database model.

Data is represented as key-value pairs, where the key and value are comprised of the following elements

Data Model


The following rules applied to all the tables in Accumulo.

  • Accumulo stores the data in key and value pair.
  • Every key consists of row id, column and timestamp. Every column has Family, Qualifier and Visibility. In the original Googles bigtable does not have Visibility column which is introduced in Accumulo.
  • All elements of the Key and the Value are represented as byte arrays except for Timestamp, which is a Long.
  • Accumulo sorts keys by element and lexicographically in ascending order.
  • Timestamps are sorted in descending order so that latest versions of the same Key appear first in a sequential scan.
  • Tables consist of a set of sorted key-value pairs after data load is done into tables.

Visibility columns is vital and holds the role of this content who can be viewed and retrieved using Scanners. You will see more about Scanners in this post.

All the write operation are logged into write-ahead log(WAL) and core xml file accumulo-site.xml.

3. Components

An instance of Accumulo includes many TabletServers, one Garbage Collector process, one Master server and many Clients. Let us have a look at these components.
  • Tablet Server
  • Garbage Collector
  • Master
  • Tracer
  • Monitor
  • Client

3.1 Tablet Server

The TabletServer manages the following as subset of the actual data tables.

  • writes and persisting writes to a write-ahead log from clients.
  • Sorting new key value pairs in memory
  • periodically flushing sorted key-value pairs to new files in HDFS
  • Responding to reads from clients
  • Forming a merge-sorted view of all keys and values from all the files it has created and the sorted in-memory store.

3.2. Garbage Collector

Periodically, the Garbage Collector will identify files that are no longer needed by any process, and delete them. Multiple garbage collectors can be run to provide hot-standby support.

3.3 Master

The Accumulo Master is responsible for detecting and responding to TabletServer failure.

3.4. Tracer

The Accumulo Tracer process supports the distributed timing API provided by Accumulo. One to many of these processes can be run on a cluster which will write the timing information to a given Accumulo table for future reference.

3.5. Monitor

The Accumulo Monitor is a web application that provides a wealth of information about the state of an instance.  Additionally, the Monitor should always be the first point of entry when attempting to debug an Accumulo problem as it will show high-level problems in addition to aggregated errors from all nodes in the cluster.

4. Fault-Tolerance

If a TabletServer fails, the Master detects it and automatically reassigns the tablets assigned from the failed server to other servers. Any key-value pairs that were in memory at the time the TabletServer fails are automatically reapplied from the Write-Ahead Log(WAL) to prevent any loss of data.

5. Accumulo Shell

This is simple shell is just to verify the configuration files and see the tables. Tables data can be updated or deleted from this shell. Configuration file setting are allowed to modify.

The shell can be started by the following command

$ACCUMULO_HOME/bin/accumulo shell -u [username]


This command will prompt for password for the specified username.

To see all the tables:

root@myinstance> tables
accumulo.metadata
accumulo.root

tables command is to print all tables under current user.

root@myinstance> createtable my-first-table

createtable command is to create a new tables in the current user. If command execution is success then no output will be printed. Now run the command "tables" to see the new table is created or not.

root@myinstance my-first-table> tables
accumulo.metadata
accumulo.root
my-first-table

Now able to see the newly created table in the list.

deletetable command is to delete the table

root@myinstance my-first-table> deletetable my-first-table

6. Running Client Code

The client code can be executed in many ways. Some of them are
  • using java executable
  • using the accumulo script
  • using the tool script

To run our program, we must add the dependencies to the classpath. Required jar files are Hadoop client jar, all of the jars in the Hadoop lib directory and the conf directory and Zookeeper jar.

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>3.2.0</version>
</dependency>


<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.14</version>
    <type>pom</type>
</dependency>

Latest jar file can be downloaded from repository for hadoop-client and zookeeper.

To see the accumulo classpath:

$ACCUMULO_HOME/bin/accumulo classpath

Once you create the jar file then place it under $ACCUMULO_HOME/lib/ext location.

To run the program:

$ACCUMULO_HOME/bin/accumulo com.foo.Client

To run the map reduce program we should use

$ACCUMULO_HOME/bin/tool.sh 

7. Connecting

Code to connect to zookeeper. Here PasswordToken should be implementation  of AuthenticationToken.

String instanceName = "myinstance";
String zooServers = "zooserver-one,zooserver-two"
Instance inst = new ZooKeeperInstance(instanceName, zooServers);

Connector conn = inst.getConnector("user", new PasswordToken("passwd"));

To use java keystore, PasswordToken must implement the CredentialProviderToken class.

8. Writing Data

To write the data into Accumulo, must have to create a mutation object which represents the all values(columns) of a single row.

8.1 Mutation creation

Mutations can be created as below. All these changes are made to TabletServer.

Text rowID = new Text("row1");
Text colFam = new Text("myColFam");
Text colQual = new Text("myColQual");
ColumnVisibility colVis = new ColumnVisibility("public");
long timestamp = System.currentTimeMillis();

Value value = new Value("myValue".getBytes());

Mutation mutation = new Mutation(rowID);
mutation.put(colFam, colQual, colVis, timestamp, value);

8.2 BatchWriter

We have to send all these mutations to the BatchWriter which submits to appropriate TabletServers.

BatchWriter is a highly optimized to send Mutations to multiple TabletServers. This handles the traffic automatically to the same TabletServer to reduce the network overhead.
But we must be taken care about chaning the contents to the mutations because BatchWriter keeps the objects in the memory while processing.

BatchWriterConfig config = new BatchWriterConfig();
config.setMaxMemory(10000000L); // bytes available to batchwriter for buffering mutations

BatchWriter writer = conn.createBatchWriter("table", config)

writer.addMutation(mutation);

writer.close();

8.3 ConditionalWriter

In some secenarios, we may want to store a few mutations and not all. We need to filter them based on the condition. This ConditionalWriter enables efficient, atomic read-modify-write operations on rows. The ConditionalWriter writes special Mutations which have a list of per column conditions that must all be met before the mutation is applied.  Examples on ConditionalWriter


9. Reading Data

Accumulo is provided a optimized way to quickly retrieve the value associated for a given key, and to efficiently return ranges of consecutive keys and their associated values.

9.1 Scanner

Scanner instance is used to retrive the objects from TabletServer. Scanner acts as Iterator to traverse through the key/value pairs.

Provides the way to provide the range for the input keys and return only wanted columns instead of all columns in the row. This Scanner class provides simplified and easy way to access the values.

Authorizations auths = new Authorizations("public");

Scanner scan =
    conn.createScanner("table", auths);

scan.setRange(new Range("harry","john"));
scan.fetchColumnFamily(new Text("attributes"));

for(Entry entry : scan) {
    Text row = entry.getKey().getRow();
    Value value = entry.getValue();
}

9.2 Isolated Scanner

Accumulo supports the ability to present an isolated view of rows when scanning. There are three possible ways that a row could change in Accumulo :

  • A mutation applied to a table
  • Iterators executed as part of a minor or major compaction
  • Bulk import of new files

For example if a mutation modifies three columns, it is possible that you will only see two of those modifications. With the isolated scanner either all three of the changes are seen or none.

  Connector conn = opts.getConnector();
    if (!conn.tableOperations().exists(opts.getTableName()))
      conn.tableOperations().create(opts.getTableName());

    Thread writer = new Thread(new Writer(conn.createBatchWriter(opts.getTableName(), bwOpts.getBatchWriterConfig()), opts.iterations));
    writer.start();
    Reader r;
    if (opts.isolated)
      r = new Reader(new IsolatedScanner(conn.createScanner(opts.getTableName(), opts.auths)));
    else
r = new Reader(conn.createScanner(opts.getTableName(), opts.auths));

9.3 BatchScanner

BatchScanner is similar to Scanner but this can be configured to get the subset of columns for a multiple ranges. BatchScanner accept a set of Ranges.

Note:
keys returned by a BatchScanner are not in sorted order since the keys streamed are from multiple TabletServers in parallel.

ArrayList ranges = new ArrayList();
// populate list of ranges ...

BatchScanner bscan =
    conn.createBatchScanner("table", auths, 10);
bscan.setRanges(ranges);
bscan.fetchColumnFamily("attributes");

for(Entry entry : bscan) {
    System.out.println(entry.getValue());
}

10. Conclusion

In this article, We have seen Accumulo data model and it's components.
In further, seen how to store the data into Accumulo data TabletServer. Diffeent ways to store and retrieving the data.