Loading...

Follow BenchResources.Net on Feedspot

Continue with Google
Continue with Facebook
or

Valid

In this article, we will discuss on how to configure http port for any Spring Boot application.

Spring Boot

As many of the Spring Boot starter aware that, an embedded Tomcat server comes with Spring-Boot-Starter which runs Spring Boot application on default Tomcat port at 8080. So default endpoint URL for Spring Boot application looks like,

http://<server-ip>:<port>/<application-context-path>
/<rest-of the-path-starting-from-controller>

But Spring Boot provides flexibility of changing default Tomcat port 8080 to our desired port as per requirement/convenience by declaring parameter-name and its designated value in application.properties file

Before that, we will develop simple Spring Boot application in step-by-step fashion to display current time to the user hitting/requesting endpoint URL

Spring Boot application development

Assumption: all are well-versed with creating Maven-based project in Eclipse IDE supporting Java 1.8 version

Step 1: Include required dependencies inside pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>in.bench.resources</groupId>
	<artifactId>SpringBootDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootDemo</name>
	<description>This is sample Spring Boot demo example for learning purpose</description>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE	</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
	</dependencies>
</project>

Step 2: Next, start with Spring Boot starter application

SpringMainApplication.java

package in.bench.resources;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringMainApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringMainApplication.class, args);
	}
}

Step 3: Let’s add controller to expose REST Web Service to return current time in String format

ExposedRestController.java

package in.bench.resources.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExposedRestController {

	// log4j2 - Logger
	Logger logger = LoggerFactory.getLogger(ExposedRestController.class);

	// Endpoint URL -> http://localhost:8080/springboot/time
	@RequestMapping("/time")
	public String exposeService() {

		logger.info("Method_Entered := exposeService");
		return "Today's date is = " + new Date();
	}
}

Step 4: Specify desired application context-path through application.properties file

# root context
server.servlet.context-path=/springboot
Directory Structure

Execution or hitting endpoint URL in browser
  • From below screen-capture, we can say that by-default Spring Boot application runs on 8080 port number
  • And application logic returns current time to the user to be displayed on the browser page
  • And it changes every time new http request sent to Controller or REST Web Service
  • Note: we can cache the result for sometime by writing/adding custom logic to controller

Spring Boot start-up
  • If you look at the below Spring boot start-up console then embedded Tomcat server started at default port number configuration i.e.; 8080
  • With our manually assigned application context-path ‘springboot
  • Click on the below image to see wording clearly

Interview Questions: 1. What are the steps to change default embedded Tomcat server port ?
  • Add one more parameter named ‘server.port‘ in application.properties in addition to already added parameter ‘server.servlet.context-path
  • And assign its value to our desired port number like 8686
  • Note: this port number is different from default tomcat server port 8080

application.properties

# root context and port
server.servlet.context-path=/springboot
server.port=8686
  • Execution and its result as shown below
2. How will you assign random port to Spring Boot application ?
  • Simply assign ‘server.port‘ value to 0 (Zero) in application.properties file
  • But we need to look into Spring Boot start-up to get to know about port number on which this application will execute/run
  • From below screen-capture, we can see that port number is 51591

application.properties

# root context and port
server.servlet.context-path=/springboot
server.port=0
  • Execution and its result as shown below
3. What if we don’t want to put port number itself ?
  • Assign ‘server.port‘ value to 80 in application.properties file
  • As default value for http request served on port number 80
  • So therefore, no need to add port number to endpoint URL

application.properties

# root context and port
server.servlet.context-path=/springboot
server.port=80
  • Execution and its result as shown below
  • From above screen-capture, it can be seen that we aren’t specifying any port number
  • Because http requests are served at port number 80, by default
Additional interesting trivia about context-path or application root-context
  • If we don’t specify context-path in application.properties file then we don’t need to add context-path to our endpoint URL
  • Similarly parameter-name that we define in application.properties file differs based on the Spring Boot version we use in our application
  • We have to use parameter-name ‘server.servlet.context-path‘ for Spring Boot 2.0 version or greater
  • Whereas for Spring Boot 2.0 or less, we have to denote with parameter-name ‘server.contextPath

Happy Coding !!
Happy Learning !!

The post Spring Boot : Interview question on port configuration appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss how to sort HashSet in Java 8. Already, in one of the earlier article we discussed about HashSet sorting in ascending & descending order

Key points about HashSet:
  • HashSet stores elements in random-order
  • Allows only unique element/objects with maximum limit of 1 null
Sorting HashSet in Java 8:
  1. With simple type like String
  2. With Object
1. Sorting HashSet with String type Steps:
  1. Create new HashSet object
  2. Add String element/objects to newly created HashSet
  3. Print original HashSet by iterating using enhanced forEach loop introduced in Java 1.5
  4. Sort using Java 1.8 stream APIs passing TreeSet as Comparator which does natural ordering of string element/objects, as shown in the above syntax
  5. Above step returns Collection<String> using Collectors 
  6. Finally iterate through returned Collection<String> using enhanced forEach loop and print to console
Syntax:
Collection<String> collection = hSetCompanies
				.stream()
				.collect(Collectors.toCollection(TreeSet::new));
SortingHashSetInJava8.java
package in.bench.resources.collection;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class SortingHashSetInJava8 {

	public static void main(String[] args) {

		// creating HashSet object of type String
		Set<String> hSetCompanies = 
				new HashSet<String>();

		// adding elements to HashSet object
		hSetCompanies.add("LinkedIn");
		hSetCompanies.add("Amazon");
		hSetCompanies.add("Google");
		hSetCompanies.add("Apple");
		hSetCompanies.add("Facebook");
		hSetCompanies.add("Oracle");
		hSetCompanies.add("Microsoft");

		// Iterating using enhanced for-loop
		System.out.println("Random-order: "
				+ "Iterating HashSet\n");
		for(String company : hSetCompanies) {
			System.out.println(company);
		}

		Collection<String> collection = hSetCompanies
				.stream()
				.collect(Collectors.toCollection(TreeSet::new));

		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending Sorting-order: "
				+ "Iterating HashSet\n");
		for(String company : collection) {
			System.out.println(company);
		}
	}
}

Output:

Random-order: Iterating HashSet

LinkedIn
Google
Apple
Microsoft
Amazon
Oracle
Facebook


Ascending Sorting-order: Iterating HashSet

Amazon
Apple
Facebook
Google
LinkedIn
Microsoft
Oracle
2. Sorting HashSet with Object Steps:
  1. First create Employee POJO along with 4-arg parameterized constructor, getter/setter and override toString() method and compareTo() method by implementing Comparable interface
  2. Create new HashSet object and add couple of Employee objects to it
  3. Print original HashSet by iterating using enhanced forEach loop introduced in Java 1.5 which will invoke toString() method to print in desired format
  4. Sort using Java 1.8 stream APIs passing class-name as Employee and desired field as getter method of name i.e.; getName() and double-colon separating them, as shown in the above syntax
  5. Above step returns List<Employee> using Collectors 
  6. Finally iterate through returned List<Employee> using enhanced forEach loop and print to console

Syntax:

// sorting using Java 1.8 stream
List<Employee> lstOfEmployee = hSetEmployees.stream()
.sorted(Comparator.comparing(
		Employee::getEmpName)) //comparator
		.collect(Collectors.toList()); //collector
Employee.java
package in.bench.resources.collection;

public class Employee implements Comparable<Employee> {

	// employee members
	String empName;
	int empId;
	int empAge;
	String empDesignation;

	// 4-arg parameterized constructor
	public Employee(String empName, int empId, 
			int empAge, String empDesignation) {
		super();
		this.empName = empName;
		this.empId = empId;
		this.empAge = empAge;
		this.empDesignation = empDesignation;
	}

	// getter & setter
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public int getEmpAge() {
		return empAge;
	}
	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}
	public String getEmpDesignation() {
		return empDesignation;
	}
	public void setEmpDesignation(String empDesignation) {
		this.empDesignation = empDesignation;
	}

	// override toString() method
	@Override
	public String toString() {
		return "Employee ["
				+ "empName=" + empName
				+ "\tempId=" + empId
				+ "\tempAge=" + empAge 
				+ "\tempDesignation=" + empDesignation
				+ "]";
	}

	// override compareTo() method
	@Override
	public int compareTo(Employee emp) {
		return this.empName.compareTo(emp.getEmpName());
	}
}
SortingHashSetObjectInJava8.java
package in.bench.resources.collection;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class SortingHashSetObjectInJava8 {

	public static void main(String[] args) {

		// creating HashSet object of type String
		Set<Employee> hSetEmployees = 
				new HashSet<Employee>();

		// creating Employee objects
		Employee employee2 = new Employee(
				"Bill G", 1001, 36, "Consultant");
		Employee employee1 = new Employee(
				"Mark Z", 1002, 30, "Engineer");
		Employee employee4 = new Employee(
				"Sundar P", 1003, 32, "Architect");
		Employee employee3 = new Employee(
				"Larry P", 1004, 25, "Designer");


		// adding Employee to HashSet object
		hSetEmployees.add(employee1);
		hSetEmployees.add(employee2);
		hSetEmployees.add(employee3);
		hSetEmployees.add(employee4);

		// Iterating using enhanced for-loop
		System.out.println("Random-order: "
				+ "Iterating Employee\n");
		hSetEmployees.forEach(
				employee -> System.out.println(employee));

		// sorting using Java 1.8 stream
		List<Employee> lstOfEmployee = hSetEmployees.stream()
				.sorted(Comparator.comparing(
						Employee::getEmpName)) //comparator
						.collect(Collectors.toList()); //collector

		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending Sorting-order: "
				+ "Iterating Employee\n");
		lstOfEmployee.forEach(
				employee -> System.out.println(employee));
	}
}

Output:

Random-order: Iterating Employee

Employee [empName=Bill G	empId=1001	empAge=36	empDesignation=Consultant]
Employee [empName=Sundar P	empId=1003	empAge=32	empDesignation=Architect]
Employee [empName=Mark Z	empId=1002	empAge=30	empDesignation=Engineer]
Employee [empName=Larry P	empId=1004	empAge=25	empDesignation=Designer]


Ascending Sorting-order: Iterating Employee

Employee [empName=Bill G	empId=1001	empAge=36	empDesignation=Consultant]
Employee [empName=Larry P	empId=1004	empAge=25	empDesignation=Designer]
Employee [empName=Mark Z	empId=1002	empAge=30	empDesignation=Engineer]
Employee [empName=Sundar P	empId=1003	empAge=32	empDesignation=Architect]

Already, we have covered sorting HashSet in different ways prior to Java 1.8 stream APIs, read those article from below links

Happy Coding !!
Happy Learning !!

The post How to sort HashSet in Java 8 ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss and execute simple program to check whether 2 Strings are Anagrams or not

Anagrams:
  • Anagrams means 2 different strings in different order but contains same characters
  • Arrangement of 2 different strings which contains same characters in different order
Anagrams program:

Steps:

  1. First, remove spaces in both strings
  2. set flag for Anagrams
  3. check length of both strings
  4. 3.a if length are not equal, then set flag to false
  5. convert both String to char[]
  6. sort both char[]
  7. check Arrays for equality, after sorting
  8. Finally, print to console
AnagramsProgram.java
package in.bench.resources.anagrams;

import java.util.Arrays;

public class AnagramsProgram {

	public static void main(String[] args) {

		// invoke checkAnagrams
		// https://ingesanagram.appspot.com/
		checkAnagrams("Silent", "Listen");
		checkAnagrams("School Master", "The Classroom");
		checkAnagrams("School Master", "The Classroom");
		checkAnagrams("Fiber", "Brief");
		checkAnagrams("Peek", "Keep");
	}

	public static void checkAnagrams(String str1, String str2) {

		// 1. remove spaces in both strings
		String string1 = str1.replaceAll("\\s", "");
		String string2 = str2.replaceAll("\\s", "");

		// 2. set flag for Anagrams
		boolean anagramsFlag = true;

		// 3. check length of both strings
		if(string1.length() != string2.length()) {
			// 3.a if length are not equal, then set flag to false
			anagramsFlag = false;
		}
		else {
			// 4. convert both String to char[]
			char[] charArray1 = string1.toLowerCase().toCharArray();
			char[] charArray2 = string2.toLowerCase().toCharArray();

			// 5. sort both char[]
			Arrays.sort(charArray1);
			Arrays.sort(charArray2);

			// 6. check Arrays for equality, after sorting
			anagramsFlag = Arrays.equals(charArray1, charArray2);  
		}

		// 7. print to console
		if(anagramsFlag) {
			System.out.println("Both " + string1 + " and " 
					+ string2 + " are Anagrams");
		}
		else {
			System.out.println(string1 + " and " 
					+ string2 + " are NOT Anagrams");
		}
	}
}

Output:

Both Silent and Listen are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both Fiber and Brief are Anagrams
Both Peek and Keep are Anagrams

Note : There are various other ways to check whether 2 Strings are Anagrams or not

Happy Coding !!
Happy Learning !!

The post How to check whether 2 strings are Anagrams in Java ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss and understand with a program to check whether HashMap is empty or not

In earlier article, we have seen how to check whether HashMap contains particular key/value or Not ? Read below articles for more details with example

  1. How to check whether a particular key is present in HashMap
  2. How to check whether a particular value is present in HashMap
To check whether HashMap is empty or not :

Method signature:

public boolean isEmpty();
  • Above method is used to check whether HashMap is empty or not from invoking Map object
  • It can be HashMap or LinkedHashMap or TreeMap
  • Returns true, if Map is empty
  • otherwise return false
HashMapIsEmptyOrNot.java
package in.bench.resources.collection;

import java.util.HashMap;

public class HashMapIsEmptyOrNot {

	public static void main(String[] args) {

		// creating empty HashMap object of type <String, String>
		HashMap<String, String> hashMap = new HashMap<String, String>();

		// checking empty even before adding any Key-Value pairs
		boolean isEmpty1 = hashMap.isEmpty();

		System.out.println("1. Checking Empty"
				+ " before adding any entries : " + isEmpty1);

		// adding key-value pairs to HashMap object
		hashMap.put("Google", "Sundar Pichai");
		hashMap.put("Facebook", "Mark Zuckerberg");
		hashMap.put("LinkedIn", "Reid Hoffman");
		hashMap.put("Apple", "Steve Jobs");
		hashMap.put("Microsoft", "Bill Gates");

		// checking empty adding few entries
		boolean isEmpty2 = hashMap.isEmpty();

		System.out.println("\n2. Checking Empty"
				+ " before adding any entries : " + isEmpty2);
	}
}

Output:

1. Checking Empty before adding any entries : true

2. Checking Empty before adding any entries : false

References:

Happy Coding !!
Happy Learning !!

The post How to check whether HashMap is empty or not ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss how to convert ArrayList to Arrays in different ways

1. Conversion of ArrayList to String Arrays using toArrays(); method

Steps :

  • Initialize ArrayList with sample values
  • Convert ArrayList to String[] Arrays using toArrays(); method, by passing to ArrayList‘s size
  • Print converted String[] Arrays in console using enhanced for-each loop

Method signature:

public Object toArrays();
ConvertArrayListToStringArrays.java
package in.bench.resources.collection;

import java.util.ArrayList;

public class ConvertArrayListToStringArrays {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Hollywood");
		al.add("Bollywood");
		al.add("Kollywood");
		al.add("Tollywood");
		al.add("Mollywood");
		al.add("Sandalwood");

		// creating String Arrays using ArrayList size
		// conversion of ArrayList to String[] Arrays
		String[] industry = al.toArray(new String[al.size()]);

		System.out.println("Conversion of "
				+ "ArrayList<String> to String[] Arrays\n");

		// print Arrays values
		for(String str : industry){
			System.out.println(str);}	
	}
}

Output:

Conversion of ArrayList<String> to String[] Arrays

Hollywood
Bollywood
Kollywood
Tollywood
Mollywood
Sandalwood
2. Conversion of List into Arrays using traditional way

Steps :

  •  Initialize ArrayList with sample values
  • create empty String[] Arrays of ArrayList size using size(); method of ArrayList
  • Iterate through original ArrayList using traditional for-loop and assign each value to of ArrayList to String[] Arrays
  • Finally, print to console using enhanced for-each loop, by iterating converted String[] Arrays
ConvertListIntoArrays.java
package in.bench.resources.collection;

import java.util.ArrayList;

public class ConvertListIntoArrays {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Hollywood");
		al.add("Bollywood");
		al.add("Kollywood");
		al.add("Tollywood");
		al.add("Mollywood");
		al.add("Sandalwood");

		// create empty String[] Arrays of ArrayList size
		String[] industry = new String[al.size()];

		// conversion of ArrayList to String[] Arrays
		// using traditional for-loop
		for(int index=0; index<industry.length; index++){

			// assign each element of AL to String[]
			industry[index] = al.get(index);
		}

		System.out.println("Conversion of "
				+ "ArrayList<String> to String[] Arrays\n");

		// print Arrays values
		for(String str : industry){
			System.out.println(str);}	
	}
}

Output:

Conversion of ArrayList<String> to String[] Arrays

Hollywood
Bollywood
Kollywood
Tollywood
Mollywood
Sandalwood

References:

Happy Coding !!
Happy Learning !!

The post Conversion of ArrayList to Arrays in Java – 2 ways appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss steps and execution program to uppercase all duplicate characters/occurrences from given String

Uppercase duplicate character in String :

Steps:

  1. Initially, create empty StringBuilder object to store all converted string
  2. first, LOWER-CASE entire original String before any operation
  3. create String[] array using space (\\s) as delimiter in split(); method of String
  4. Iterate through original String after split (Outer for-loop)
  5. while iterating, store split’ed string in temporary variable
  6. create LinkedHashSet to check/store duplicate occurrences
  7. convert temp String into character-array (char[]) using toCharArray(); method
  8. Iterate through converted char[] array (Inner for-each loop)
  9. check whether char already present in LinkedHashSet, while iterating Inner for-loop
  10. If not present, then add to LinkedHashSet using add(); method as well as StringBuilder using append(); method
  11. If present, then store duplicate character in StringBuilder after converting to UPPER-CASE
  12. add single space to StringBuilder after each iteration of Outer for-loop
  13. finally pretty print to console
UpperCaseDuplicateCharacterInString.java
package in.bench.resources.collection;

import java.util.LinkedHashSet;
import java.util.Set;

public class UpperCaseDuplicateCharacterInString {

	public static void main(String[] args) {

		// sample test string
		String testStr = "madam sss gg fff rr malayalam";
		Set<Character> lhSet = null;

		// Step 1: create StringBuilder object 
		// to store converted strings
		StringBuilder sbuilder = new StringBuilder();

		// Step 2: first, LOWER-CASE entire String before any operation
		String lowerStr = testStr.toLowerCase();

		// Step 3: create String[] using 
		// space as delimiter in split() method of String
		String[] strArray = lowerStr.split("\\s");

		// Step 4: Iterate original String after split
		for(int index=0; index < strArray.length; index++) {

			// Step 5: store it in temporary variable
			String temp = strArray[index];

			// Step 6: create LinkedHashSet to check/store duplicate
			lhSet = new LinkedHashSet<Character>();

			// Step 7: convert temp String into character-array 
			// using toCharArray() method 
			char[] chArray = temp.toCharArray();

			// Step 8: iterate through converted char[] array
			for(char ch : chArray) {

				// Step 9: check whether char already present in LHSet
				boolean checkChar = lhSet.contains(ch);

				// Step 10: if not present, then add
				if(!checkChar) {
					lhSet.add(ch);
					sbuilder.append(ch);
				}
				else {
					// Step 11: if present, then store duplicate 
					// after converting to UPPER-CASE in StringBuilder 
					sbuilder.append(Character.toUpperCase(ch));
				}
			}

			// Step 12: add single space after outer for-loop
			sbuilder.append(" ");
		}

		// Step 13: finally pretty print to console
		System.out.println("Original String  : " 
				+ testStr);
		System.out.println("\nConverted String : " 
				+ sbuilder.toString().trim());
	}
}

Output :

Original String  : madam sss gg fff rr malayalam

Converted String : madAM sSS gG fFF rR malAyALAM

Happy Coding !!
Happy Learning !!

The post Java – How to uppercase every duplicate character in String ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss steps and execution program to delete/remove all duplicate characters/occurrences from given String

Remove duplicate characters from String in Java :

Steps:

  1. Create LinkedHashSet to maintain insertion-order
  2. Convert given/test String into character-array using toCharArray(); method
  3. Iterate through char[] array using enhanced for-each loop
  4. Leave spaces, as it isn’t considered while deleting/removing duplicate occurrences/characters
  5. While iterating, check whether character already present in LinkedHashSet
  6. If not present in LinkedHashSet, then add that particular character into LinkedHashSet using add(); method; otherwise leave it, as it is duplicate character/occurence
  7. finally, print to console
RemoveDuplicateFromString.java
package in.bench.resources.collection;

import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateFromString {

	public static void main(String[] args) {

		// sample test string
		String testStr = "SSS FFF GG RR";

		// Step 1: create LinkedHashSet to maintain insertion-order
		Set<Character> lhSet = new LinkedHashSet<Character>();

		// Step 2: convert String into character-array 
		// using toCharArray() method 
		char[] chArray = testStr.toCharArray();

		// Step 3: iterate through char[] array
		for(char ch : chArray) {

			// Step 4: leave spaces
			if(ch != ' '){

				// Step 5: check whether char already present in LHSet
				boolean checkChar = lhSet.contains(ch);

				// Step 6: if not present, then add
				if(!checkChar) {
					lhSet.add(ch);
				}
			}
		}

		// Step 7: print to console
		System.out.println("After removing duplicate : " + lhSet);
	}
}

Output:

After removing duplicate : [S, F, G, R]

Happy Coding !!
Happy Learning !!

The post Remove duplicate characters from String in Java appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss how to convert ordered LinkedHashMap into Sorted TreeMap by its Values

Sorting LinkedHashMap by Values: Ascending order sorting:
  1. get entrySet() from Map
  2. create List of entries using entry set
  3. sort using Collections class, by implementing Comparator for natural ordering of String objects
  4. clear original LinkedHashMap
  5. Iterate List and add entries to original LinkedHashMap , after clearing
  6. finally print Map.Entry in console
  7. Read Example 1 – Sorting in ascending order by its values
Descending order sorting:
  1. get entrySet() from Map
  2. create List of entries using entry set
  3. sort using Collections class, by implementing Comparator for reverse sorting logic for String objects
  4. clear original LinkedHashMap
  5. Iterate List and add entries to original LinkedHashMap , after clearing
  6. finally print Map.Entry in console
  7. Read Example 2 – Sorting in descending order by its values
Example 1: Sorting in ascending order of Values:
  • LinkedHashMap maintains insertion-order
  • In below demo example, we will sort/convert LinkedHashMap into natural-ordering of Values
SortingLinkedHashMapInAscOrderByValues.java
package in.bench.resources.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortingLinkedHashMapInAscOrderByValues {

	public static void main(String[] args) {

		// creating LinkedHashMap object of type <String, String>
		Map<String, String> linkMap = 
				new LinkedHashMap<String, String>(); 

		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("Facebook", "Mark Zuckerberg");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Apple", "Tim Cook");
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Amazon", "Jeff Bezos");
		linkMap.put("Oracle", "Larry Ellison");

		System.out.println("Before Sorting by Values -"
				+ " as per insertion-order : \n");

		// iterate original LinkedHashMap
		for(Map.Entry<String, String> lhmap : 
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() 
					+ "\t\t" + "Value : "  + lhmap.getValue());
		}

		// 1. get entrySet from LinkedHashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				linkMap.entrySet();

		// 2. convert LinkedHashMap to List of Map.Entry
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(
						companyFounderSet);

		// 3. sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		Collections.sort(companyFounderListEntry, 
				new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> es1, 
					Entry<String, String> es2) {
				return es1.getValue().compareTo(es2.getValue());
			}
		});

		// 4. clear original LinkedHashMap
		linkMap.clear();

		// 5. iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			linkMap.put(map.getKey(), map.getValue());
		}

		System.out.println("\n\nSorted LinkedHashMap by its Values"
				+ " in ascending-order\n");

		// iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap : 
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() 
					+ "\t\t" + "Value : "  + lhmap.getValue());
		}
	}
}

Output:

Before Sorting by Values - as per insertion-order : 

Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Apple		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison


Sorted LinkedHashMap by its Values in ascending-order

Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Apple		Value : Tim Cook
Example 2: Sorting in descending order of Values:
  • LinkedHashMap maintains insertion-order
  • In below demo example, we will sort/convert LinkedHashMap into reverse-ordering of Values
SortingLinkedHashMapInDesOrderByValues.java
package in.bench.resources.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class SortingLinkedHashMapInDesOrderByValues {

	public static void main(String[] args) {

		// creating LinkedHashMap object of type <String, String>
		Map<String, String> linkMap = 
				new LinkedHashMap<String, String>(); 

		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("Facebook", "Mark Zuckerberg");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Apple", "Tim Cook");
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Amazon", "Jeff Bezos");
		linkMap.put("Oracle", "Larry Ellison");

		System.out.println("Before Sorting by Values -"
				+ " as per insertion-order : \n");

		// iterate original LinkedHashMap
		for(Map.Entry<String, String> lhmap : 
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() 
					+ "\t\t" + "Value : "  + lhmap.getValue());
		}

		// 1. get entrySet from LinkedHashMap object
		Set<Map.Entry<String, String>> companyFounderSet = 
				linkMap.entrySet();

		// 2. convert LinkedHashMap to List of Map.Entry
		List<Map.Entry<String, String>> companyFounderListEntry = 
				new ArrayList<Map.Entry<String, String>>(
						companyFounderSet);

		// 3. sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		Collections.sort(companyFounderListEntry, 
				new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> es1, 
					Entry<String, String> es2) {
				return es2.getValue().compareTo(es1.getValue());
			}
		});

		// 4. clear original LinkedHashMap
		linkMap.clear();

		// 5. iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			linkMap.put(map.getKey(), map.getValue());
		}

		System.out.println("\n\nSorted LinkedHashMap by its Values"
				+ " in descending-order\n");

		// iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap : 
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey() 
					+ "\t\t" + "Value : "  + lhmap.getValue());
		}
	}

}

Output:

Before Sorting by Values - as per insertion-order : 

Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Apple		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison


Sorted LinkedHashMap by its Values in descending-order

Key : Apple		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg
Key : Oracle		Value : Larry Ellison
Key : Amazon		Value : Jeff Bezos
Key : Microsoft		Value : Bill Gates
Important points:
  • HashMap stores entries (key-value pairs) in random-order
  • LinkedHashMap stores entries (key-value pairs) as per insertion-order
  • TreeMap stores entries (key-value pairs) in some sorting-order

References:

The post How to sort LinkedHashMap by its Values ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss how to convert ordered LinkedHashMap into Sorted TreeMap by its Keys

Sorting LinkedHashMap in both Ascending/descending order:
  1. Ascending order: pass LinkedHashMap entries as arguments to TreeMap class’ inter-conversion constructor
  2. Descending order: Implement Comparator interface by providing reverse sorting logic and finally putting all entries of HashMap into TreeMap classs using putAll() method
Example 1: Sorting in ascending order of keys:
  • LinkedHashMap maintains insertion-order
  • In below demo example, we will sort/convert LinkedHashMap into natural-ordering of keys
Syntax:
// convert to TreeMap
Map<String, String> ts = new TreeMap<String, String>(linkMap);
SortingLinkedHashMapInAscOrder.java
package in.bench.resources.collection;

import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortingLinkedHashMapInAscOrder {

	public static void main(String[] args) {

		// creating LinkedHashMap object of type <String, String>
		LinkedHashMap<String, String> linkMap = 
				new LinkedHashMap<String, String>(); 

		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Apple", "Steve Jobs");
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Facebook", "Mark Zuckerberg");

		// Insertion-Order iterating
		System.out.println("Before Sorting : Insertion-Order \n");

		// getting keySet() into Set
		Set<String> set = linkMap.keySet();

		// get Iterator from key set
		Iterator<String> itr = set.iterator();

		// iterating in Insertion-order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key 
					+ "\t\t" + "Value : "  + linkMap.get(key));
		}

		// After Sorting : Ascending order
		System.out.println("\n\n\nAfter Sorting : Ascending-Order\n");

		// convert to TreeMap
		Map<String, String> ts = new TreeMap<String, String>(linkMap);

		// iterate acc to ascending order of keys
		for(String strKey : ts.keySet()){
			System.out.println("Key : "  + strKey 
					+ "\t\t" + "Value : "  + linkMap.get(strKey));
		}
	}
}

Output:

Before Sorting : Insertion-Order 

Key : Microsoft		Value : Bill Gates
Key : Apple		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Ascending-Order

Key : Apple		Value : Steve Jobs
Key : Facebook		Value : Mark Zuckerberg
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates
Example 2: Sorting in descending order of keys:
  • LinkedHashMap maintains insertion-order
  • In below demo example, we will sort/convert LinkedHashMap into reverse-ordering of keys
Syntax:
// convert to TreeMap
		// descending or reverse-order sorting logic
		Map<String, String> tMap = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				});

		// put all key-value into TreeMap
		tMap.putAll(linkMap);
SortingLinkedHashMapInDesOrder.java
package in.bench.resources.collection;

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortingLinkedHashMapInDesOrder {

	public static void main(String[] args) {

		// creating LinkedHashMap object of type <String, String>
		LinkedHashMap<String, String> linkMap = 
				new LinkedHashMap<String, String>(); 

		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Apple", "Steve Jobs");
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Facebook", "Mark Zuckerberg");

		// Insertion-Order iterating
		System.out.println("Before Sorting : Insertion-Order \n");

		// getting keySet() into Set
		Set<String> set = linkMap.keySet();

		// get Iterator from key set
		Iterator<String> itr = set.iterator();

		// iterating in insertion-order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key 
					+ "\t\t" + "Value : "  + linkMap.get(key));
		}

		// After Sorting : Descending order
		System.out.println("\n\n\nAfter Sorting : Descending-Order\n");

		// convert to TreeMap
		// descending or reverse-order sorting logic
		Map<String, String> tMap = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				});

		// put all key-value into TreeMap
		tMap.putAll(linkMap);

		// iterate acc to descending order of keys
		for(String strKey : tMap.keySet()){
			System.out.println("Key : "  + strKey 
					+ "\t\t" + "Value : "  + linkMap.get(strKey));
		}
	}
}

Output:

Before Sorting : Insertion-Order 

Key : Microsoft		Value : Bill Gates
Key : Apple		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Descending-Order

Key : Microsoft		Value : Bill Gates
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : Apple		Value : Steve Jobs
Important points:
  • HashMap stores entries (key-value pairs) in random-order
  • LinkedHashMap stores entries (key-value pairs) as per insertion-order
  • TreeMap stores entries (key-value pairs) in some sorting-order

References:

The post How to sort LinkedHashMap by its Keys ? appeared first on BenchResources.Net.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this article, we will discuss how to sort contents of LinkedHashSet

Key points about LinkedList:
  • LinkedHashSet maintains insertion-order
  • as it uses doubly-linked list and hash table to store element/objects
Different ways to sort LinkedHashSet :
  1. Convert LinkedHashSet to TreeSet for natural-ordering
  2. Convert LinkedHashSet to TreeSet for reverse-ordering by providing Comparator based customized-sorting logic
  3. Using ArrayList and Collections class’ utility method sort();

Let us move forward to discuss different ways to sort LinkedHashSet contents

Way 1: Convert LinkedHashSet to TreeSet for natural-ordering

Steps:

  • Create new LinkedHashSet object
  • Store/add contents to LinkedHashSet
  • Create new TreeSet object,
  • Pass LinkedHashSet contents as argument to TreeSet’ inter-conversion constructor

Syntax:

// convert LinkedHashSet to TreeSet
TreeSet<String> tSet = new TreeSet<String>(lhsCompanies); 
SortingLinkedHashSetUsingTreeSet.java
package in.bench.resources.collection;

import java.util.LinkedHashSet;
import java.util.TreeSet;

public class SortingLinkedHashSetUsingTreeSet {

	public static void main(String[] args) {

		// creating LinkedHashSet object of type String
		LinkedHashSet<String> lhsCompanies = 
				new LinkedHashSet<String>();

		// adding elements to LinkedHashSet object
		lhsCompanies.add("LinkedIn");
		lhsCompanies.add("Amazon");
		lhsCompanies.add("Google");
		lhsCompanies.add("Apple");
		lhsCompanies.add("Facebook");
		lhsCompanies.add("Oracle");
		lhsCompanies.add("Microsoft");

		// Iterating using enhanced for-loop
		System.out.println("Insertion Order:"
				+ " Iterating LinkedHashSet\n");
		for(String company : lhsCompanies) {
			System.out.println(company);
		}

		// convert LinkedHashSet to TreeSet
		TreeSet<String> tSet = new TreeSet<String>(lhsCompanies); 

		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending sorting-order:"
				+ " Iterating TreeSet\n");
		for(String company : tSet) {
			System.out.println(company);
		}
	}
}

Output:

Insertion Order: Iterating LinkedHashSet

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft


Ascending sorting-order: Iterating TreeSet

Amazon
Apple
Facebook
Google
LinkedIn
Microsoft
Oracle
Way 2: Convert LinkedHashSet to TreeSet for reverse-ordering

Steps:

  • Create new LinkedHashSet object
  • Store/add contents to LinkedHashSet
  • Create new TreeSet object and provide reverse-order sorting-logic using Comparator
  • Add LinkedHashSet contents  to TreeSet using addAll(); method

Syntax:

// create new TreeSet object and provide reverse-sorting logic
		TreeSet<String> tSet = new TreeSet<String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				}); 

		// add LinkedHashSet to TreeSet for reverse-sorting elements
		tSet.addAll(lhsCompanies);
ReverseSortingLinkedHashSetUsingTreeSet.java
package in.bench.resources.collection;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.TreeSet;

public class ReverseSortingLinkedHashSetUsingTreeSet {

	public static void main(String[] args) {

		// creating LinkedHashSet object of type String
		LinkedHashSet<String> lhsCompanies = 
				new LinkedHashSet<String>();

		// adding elements to LinkedHashSet object
		lhsCompanies.add("LinkedIn");
		lhsCompanies.add("Amazon");
		lhsCompanies.add("Google");
		lhsCompanies.add("Apple");
		lhsCompanies.add("Facebook");
		lhsCompanies.add("Oracle");
		lhsCompanies.add("Microsoft");

		// Iterating using enhanced for-loop
		System.out.println("Insertion Order:"
				+ " Iterating LinkedHashSet\n");
		for(String company : lhsCompanies) {
			System.out.println(company);
		}

		// create new TreeSet object and provide reverse-sorting logic
		TreeSet<String> tSet = new TreeSet<String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				}); 

		// add LinkedHashSet to TreeSet for reverse-sorting elements
		tSet.addAll(lhsCompanies);

		// Iterating using enhanced for-loop
		System.out.println("\n\nDescending sorting-order:"
				+ " Iterating TreeSet\n");
		for(String company : tSet) {
			System.out.println(company);
		}
	}
}

Output:

Insertion Order: Iterating LinkedHashSet

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft


Descending sorting-order: Iterating TreeSet

Oracle
Microsoft
LinkedIn
Google
Facebook
Apple
Amazon
Way 3: Using ArrayList and Collections’ class utility method sort();

Steps:

  • Create new LinkedHashSet object
  • Store/add contents to LinkedHashSet
  • Convert LinkedHashSet to ArrayList using inter-conversion constructor
  • Invoke sort(); method on ArrayList contents using Collections‘ class
  • Invoke clear(); method on original LinkedHashSet, if we want to convert back ArrayList to LinkedHashSet
  • Finally, convert ArrayList to LinkedHashSet by adding ArrayList contents to LinkedHashSet, as LinkedHashSet maintains insertion-order, if we want to retain original LinkedHashSet
  • Note : we can sort in reverse-order using Comparator and providing reverse-order sorting logic

Syntax:

// convert LinkedHashSet to ArrayList
List<String> lst = new ArrayList<String>(lhsCompanies);

// sort using Collections class
Collections.sort(lst);

// clear or empty LinkedHashSet
lhsCompanies.clear();

// convert sorted ArrayList to LinkedHashSet, afetr clear();
lhsCompanies.addAll(lst);
SortingLinkedHashSetUsingArrayList.java
package in.bench.resources.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;

public class SortingLinkedHashSetUsingArrayList {

	public static void main(String[] args) {

		// creating LinkedHashSet object of type String
		LinkedHashSet<String> lhsCompanies = 
				new LinkedHashSet<String>();

		// adding elements to LinkedHashSet object
		lhsCompanies.add("LinkedIn");
		lhsCompanies.add("Amazon");
		lhsCompanies.add("Google");
		lhsCompanies.add("Apple");
		lhsCompanies.add("Facebook");
		lhsCompanies.add("Oracle");
		lhsCompanies.add("Microsoft");

		// Iterating using enhanced for-loop
		System.out.println("Insertion Order:"
				+ " Iterating LinkedHashSet\n");
		for(String company : lhsCompanies) {
			System.out.println(company);
		}

		// convert LinkedHashSet to ArrayList
		List<String> lst = new ArrayList<String>(lhsCompanies);

		// sort using Collections class
		Collections.sort(lst);

		// clear or empty LinkedHashSet
		lhsCompanies.clear();

		// convert sorted ArrayList to LinkedHashSet, afetr clear();
		lhsCompanies.addAll(lst);

		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending sorting-order:"
				+ " Iterating LinkedHashSet\n");
		for(String company : lhsCompanies) {
			System.out.println(company);
		}
	}
}

Output:

Insertion Order: Iterating LinkedHashSet

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft


Ascending sorting-order: Iterating LinkedHashSet

Amazon
Apple
Facebook
Google
LinkedIn
Microsoft
Oracle

References:

Happy Coding !!
Happy Learning !!

The post How to sort LinkedHashSet contents in Java ? appeared first on BenchResources.Net.

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview