Java @ Desk

Java @ Desk

Breaking

Thursday, January 2, 2025

How to capitalize first letter of each word in a String in Python

3:10 AM 0

Wednesday, January 1, 2025

How to substring a string in Python

5:23 AM 0
Substring a string in Python is done using the below syntax -
str = 'OriginalString';
substring_start = str[:8]
print("Substring first 8 characters - " + substring_start)

substring_end = str[8:]
print("Substring last 8 characters - " + substring_end)

Output -

Substring first 8 characters - Original
Substring last 8 characters - String

Thursday, April 21, 2022

Python remove leading and trailing white space from a String

7:21 AM 0
Python remove leading and trailing white space from a String

Python have 3 functions to remove the trimmed space, remove leading whitespace and remove trailing whitespace.

strip(): Removes leading and trailing whitespace.
rstrip(): Removes trailing whitespace.
lstrip(): Removes leading whitespace.

 string = '  Python Trim String  '  
 print('Original String is - \'' + string + '\'')  
 print('Removing Trailing Space - \'' + string.rstrip()+ '\'')  
 print('Removing Leading Space - \'' + string.lstrip()+ '\'')  
 print('Trimmed String is - \'' + string.strip()+ '\'')  


Output :

 Original String is - '  Python Trim String  '  
 Trimmed String is - 'Python Trim String'  
 Removing Trailing Space - '  Python Trim String'  
 Removing Leading Space - 'Python Trim String  '  

Monday, December 14, 2020

AtomicInteger and volatile in Multithreading Java

12:42 AM 0
AtomicInteger and volatile in Multithreading Java

In our previous post, we learnt about the volatile keyword in Java. But volatile keyword is not sufficient to guarantee atomicity. Volatility just guarantees the visibility of the variable and NOT atomicity, whereas Synchronization (locking) guarantees both visibility and atomicity.
But Synchronization affects processing time.
By visibility we mean that all the threads will get the latest form of the variable. In the above example, as you can see, all the threads get the latest value of counter in the subsequent reads.

AtomicInteger helps in getting the latest value of the last write by any given thread in a Multithreading environment. If we have multiple threads that reads and writes the integer, then AtomicInteger guarantees, the write operation must get the latest update from the memory.

AtomicIntegerExample.java - In this class, we have 2 variables, one is Integer and another is AtomicInteger. We have created 2 Threads that updates the values of both the fields by 1. This update operation is running 10000 times by 2 different threads. So final values expected for both the fields must be -
1) atomicInteger - 20000
2) integer - 20000

But since integer variable is just volatile, then multiple threads do not get the latest value during write. But that is taken care by the AtomicInteger as shown below -


package com.learning;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample implements Runnable {

	@Override
	public void run() {
		int max = 10000;

		for (int i = 0; i < max; i++) {
			atomicInteger.addAndGet(1);
			integer = integer + 1;
		}
	}

	public static void main(String args[]) throws InterruptedException {
		AtomicIntegerExample atomicIntegerExample = new AtomicIntegerExample();
		atomicIntegerExample.setAtomicInteger(new AtomicInteger());
		atomicIntegerExample.setInteger(new Integer(0));

		Thread first = new Thread(atomicIntegerExample);
		Thread second = new Thread(atomicIntegerExample);

		// Threads start executing
		first.start();
		second.start();

		// main thread will wait for both threads to complete execution
		first.join();
		second.join();

		// Printing final value of count variable
		System.out.println("Atomic Integer in Multithreading - " + atomicIntegerExample.getAtomicInteger());
		System.out.println("Integer Value in Multithreading - " + atomicIntegerExample.getInteger());
	}

	private AtomicInteger atomicInteger;

	private volatile Integer integer;

	public AtomicInteger getAtomicInteger() {
		return atomicInteger;
	}

	public void setAtomicInteger(AtomicInteger atomicInteger) {
		this.atomicInteger = atomicInteger;
	}

	public Integer getInteger() {
		return integer;
	}

	public void setInteger(Integer integer) {
		this.integer = integer;
	}

}




Output - Results of 5 different executions. Its clearly visible, AtomicInteger is safely incremented by 1 and all threads get the latest updates of the variable.


Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11354

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11681

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 12656

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11107

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 13106


Friday, December 11, 2020

Stream Intermediate vs Terminal Operation in Java 8

11:14 PM 0
Stream Intermediate vs Terminal Operation in Java 8

In Java 8, Stream is used to perform operations in pipeline to either get another Stream or Collection or Object. Stream operations are performed on objects that are returning Stream and not on any other type.

The Stream operation that returns another Stream is an Intermediary Operation. Hence these can be chained together to form a Pipeline. Basic example is, we can perform filter operations on a Stream to remove Null objects from a Collection - ".filter(Objects::nonNull)", then perform another filter operation on returned Stream as per business logic i.e. ".filter(person -> person.getGender().equals(Gender.MALE))". We can have multiple Intermediate Operations as shown above. They are lazily loaded. They are just stored in the memory and executed when the terminal operation is called on the stream.

The Stream operation that returns anything other than Stream i.e. Object or a Collection type is an Terminal Operation. These operations cannot be chained together. We can have only 1 Terminal Operations at the end.

Stream Operations - filter(), map(), limit(), skip()
Intermediate Operations - forEach(), collect(), count(), min(), max(), etc.

IntermediaryTerminalStream.java - In this example, we will learn 2 Intermediate(filter & map) and 2 Terminal(collect & count).


package com.learning;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.learning.model.Gender;
import com.learning.model.Person;

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

		List persons = new ArrayList<>();
		Person personOne = new Person(10, "John", Gender.MALE);
		Person personTwo = new Person(11, "Andy", Gender.MALE);
		Person personThree = new Person(12, "Peter", Gender.MALE);
		Person personFour = new Person(13, "Sarah", Gender.FEMALE);
		Person personFive = new Person(14, "Gillian", Gender.FEMALE);

		persons.add(personOne);
		persons.add(personTwo);
		persons.add(personThree);
		persons.add(personFour);
		persons.add(personFive);

		// Filter is a Intermediate Operation, since it returns a Stream and we can
		// perform
		// Terminal Operations on them.
		Stream filterIntermediateOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE));

		// map is a Intermediate Operation, since it returns a Stream and we can perform
		// Terminal Operations on them.
		Stream mapIntermediateOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).map(Person::getName);

		// collect is a Terminal Operation. No Intermediary operations can be performed,
		// since its returning a List instead of Stream.
		List collectTerminalOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).collect(Collectors.toList());

		// count is a Terminal Operation. No Intermediary operations can be performed,
		// since its returning a Integer instead of Stream.
		Integer countTerminalOperation = (int) persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).count();

	}
}



Sunday, December 6, 2020

How to use Streams in Map in Java 8

6:01 AM 0
How to use Streams in Map in Java 8

Map, unlike, other Collection types is in a Key/Value Format where the Keys are unique in a Map. Using Map.Entry, we can fetch the keySet() as well as entrySet().
Stream cannot be applied directly to a Map since Stream is done on the Collection of Objects. So it is applied to a keySet() or a entrySet() or values() that return the collection of value from a Map.



Map someMap = new HashMap<>();
Set> entries = someMap.entrySet();
Set keySet = someMap.keySet();
Collection values = someMap.values();
These each give us an entry point to process those collections by obtaining streams from them:

Stream> entriesStream = entries.stream();
Stream valuesStream = values.stream();
Stream keysStream = keySet.stream();



Here are few examples of Stream for a Map


package com.learning;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import com.learning.model.Gender;
import com.learning.model.Person;

public class StreamMap {

	public static void main(String args[]) {
		Map personMap = new HashMap();

		Person personOne = new Person(10, "John", Gender.MALE);
		Person personTwo = new Person(11, "Andy", Gender.MALE);
		Person personThree = new Person(12, "Peter", Gender.MALE);
		Person personFour = new Person(13, "Sarah", Gender.FEMALE);
		Person personFive = new Person(14, "Gillian", Gender.FEMALE);

		personMap.put(personOne.getAge(), personOne);
		personMap.put(personTwo.getAge(), personTwo);
		personMap.put(personThree.getAge(), personThree);
		personMap.put(personFour.getAge(), personFour);
		personMap.put(personFive.getAge(), personFive);

		// Find all Person Objects where Age is Even
		System.out.println("Persons with Even Age - " + personMap.entrySet().stream().filter(person -> person.getKey() % 2 == 0)
				.map(Map.Entry::getValue).collect(Collectors.toList()));

		// Find all Person Objects where Gender is Female
		System.out.println("Persons with Gender Female - " + personMap.values().stream().filter(person -> person.getGender().equals(Gender.FEMALE))
				.collect(Collectors.toList()));

	}
}



Output


Persons with Even Age - [10 John MALE, 12 Peter MALE, 14 Gillian FEMALE]
Persons with Gender Female - [13 Sarah FEMALE, 14 Gillian FEMALE]



Tuesday, February 25, 2020

How to get sum of Integer or Double field from a List of Pojo Java class

6:52 AM 0
How to get sum of Integer or Double field from a List of Pojo Java class

This post will demonstrate how to get sum of any particular field, for example, consider a List of Person class with property noOfMangoesEaten which represents how many mangoes an individual has consumed.

Using Java 8, we need to find how many mangoes in total have been consumed by all the persons inside a List.

We can use streams function to iterate the list and use mapToInteger function and gets sum out of it.

Here is an example

Person.java
package com.test;

public class Person {

 private int noOfMangoesConsumed;

 public int getNoOfMangoesConsumed() {
  return noOfMangoesConsumed;
 }

 public void setNoOfMangoesConsumed(int noOfMangoesConsumed) {
  this.noOfMangoesConsumed = noOfMangoesConsumed;
 }
}


SumOfFields.java -
package com.test;

import java.util.ArrayList;
import java.util.List;

public class SumOfFields {

 public static void main(String args[]) {
  Person person = new Person();
  person.setNoOfMangoesConsumed(100);
  
  Person person2 = new Person();
  person2.setNoOfMangoesConsumed(200);
  
  List<Person> persons = new ArrayList<Person>();
  persons.add(person);
  persons.add(person2);
  
  int sum = persons.stream().mapToInt(p -> p.getNoOfMangoesConsumed()).sum();
  
  System.out.println("Total Mangoes Consumed - " + sum);
 }
}


Output -
Total Mangoes Consumed - 300

Friday, January 25, 2019

Spring Validator Framework In Java

11:57 PM 0
Spring Validator Framework In Java

Spring Validator Framework validates the input Java class properties. Validator class must implement org.springframework.validation.Validator and define the validator rules in the overridden method -
public void validate(Object o, Errors errors)

This method contains the validation rules. For example, for a Person class validation rules can be to verify if name, address properties of the incoming Person class are not null and not empty.

org.springframework.validation.ValidationUtils invokes the validation on the incoming Person class by using the Validator Implemention that defined the validation rules.

There are 2 ways to invoke validation on the incoming objects -
1) ValidationUtils.invokeValidator(personValidator, person, errors); - personValidator is the class implementing Validation interface and errors is the object of class BindException
2) personValidator.validate(person, errors);

Here is a sample implementation of the Spring Validation Framework

Person.java
package com.learning.com.springvalidation;

public class Person {

    private String name;

    private int age;

    private String address;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


PersonValidator.java
package com.learning.com.springvalidation;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {
    public boolean supports(Class<?> aClass) {
        return Person.class.isAssignableFrom(aClass);
    }

    public void validate(Object o, Errors errors) {

        if (o == null) {
            errors.reject("Person Object is Null");
        }
        Person person = (Person) o;
        if (person.getName() == null) {
            errors.reject("Name Field Is Null");
        }
        if (person.getAddress() == null) {
            errors.reject("Address Field Is Null");
        }
    }
}


PersonClient.java
package com.learning.com.springvalidation;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;

public class PersonClient {

    public static void main(String args[]) {
        PersonValidator personValidator = new PersonValidator();
        Person person = new Person();
        BindException errors = new BindException(person, "person");
        ValidationUtils.invokeValidator(personValidator, person, errors);
        System.out.println("Error - " + errors.getMessage());
    }
}


Output
"C:\Program Files\Java\jdk1.8.0_181\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\lib\idea_rt.jar=53398:C:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;C:\Kumar\Projects\learning\target\classes;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-context\5.1.4.RELEASE\spring-context-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-aop\5.1.4.RELEASE\spring-aop-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-beans\5.1.4.RELEASE\spring-beans-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-core\5.1.4.RELEASE\spring-core-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-jcl\5.1.4.RELEASE\spring-jcl-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-expression\5.1.4.RELEASE\spring-expression-5.1.4.RELEASE.jar" com.learning.com.springvalidation.PersonClient
Error - org.springframework.validation.BeanPropertyBindingResult: 2 errors
Error in object 'person': codes [Name Field Is Null.person,Name Field Is Null]; arguments []; default message [null]
Error in object 'person': codes [Address Field Is Null.person,Address Field Is Null]; arguments []; default message [null]

Process finished with exit code 0