Showing posts with label java8. Show all posts
Showing posts with label java8. Show all posts

Saturday, 30 September 2023

Difference Between PermGen (Permanent Generation) and Metaspace in Java

        In this post, we will discuss the differences between PermGen (Permanent Generation) and Metaspace in Java.

Before Java 8, class metadata was stored in the PermGen (Permanent Generation) memory space. If the allocated PermGen space was exhausted, the JVM threw an OutOfMemoryError. By default, the PermGen size was limited, and if required, it could be increased using JVM options such as -XX:MaxPermSize.

Java 8 removed PermGen and introduced Metaspace to address these limitations. Unlike PermGen, Metaspace stores class metadata in native memory rather than in the JVM heap. By default, Metaspace automatically expands as needed (subject to the available native memory), eliminating the need to manually increase its size in most cases. If required, its maximum size can still be limited using the -XX:MaxMetaspaceSize JVM option.

PermGen and Metaspace difference

Thank you for visiting the blog.

Wednesday, 16 August 2023

Java 8 Optional Class with Examples

         Java 8 introduced a new class called Optional, which helps handle NullPointerException without requiring explicit null checks. (Refer to: Java 8 Features.) It provides several utility methods that make the code more readable, maintainable, and cleaner.

When a value is null, you can use methods such as orElse() to provide a default value or execute alternative logic.

Below are some of the commonly used methods available in the Optional class:

Java 8 optional class methods

The Optional.ofNullable() --- > method returns a Non-empty Optional if a value present in the given object. Otherwise returns an empty Optional. 

Optional.empty() -- > method is useful to create an empty Optional object.

Optional.of(value) --> creates an Optional object using value. 

Optional.ifPresent -- > If optional variable value is present, invoke the specified consumer with the value, otherwise, do nothing.

orElse --> If optional variable value is null then invokes orElse method.

 orElseGet --> If optional variable value is null then invokes orElse method and return the result of that invocation.

 orElseThrow --> If optional variable value is null then invokes orElseThrow method and throws the exception provided in the method.

 get -- > method returns the value from the optional.

 isPresent - if optional variable value is present/exist then return true else it's false.


Optional Class Code Example - 

import java.util.Optional;

public class OptionalClassUsages {
	
	public static void main(String[] args) {
		
		//ofNullable, orElse, orElseGet and orElseThrow method example
		String str = "Optional with ofNullable method usage";
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		
		str = null;
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		System.out.println(Optional.ofNullable(str).orElseGet(() -> "orElseGet method"));
		
		try {
			Optional.ofNullable(str).orElseThrow(() -> {
				return new Exception("orElseThrow Exception");
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//optional of, ifPresent, filter usages
		Optional<String> optional = Optional.of("ab");
		optional.ifPresent(s-> System.out.println(s));
		optional.filter(s->s.equals("ab"))
				.ifPresent(s-> System.out.println("ifPresent method usage"));
		
		//isPresent and get method usage example
		System.out.println(optional.isPresent());
		System.out.println(optional.get());	
	}
}

Output:- 

Optional with ofNullable method usage
null logic
orElseGet method
java.lang.Exception: orElseThrow Exception
	at com.main.OptionalClassUsages.lambda$1(OptionalClassUsages.java:19)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at com.main.OptionalClassUsages.main(OptionalClassUsages.java:18)
ab
ifPresent method usage
true
ab


Thank you for visiting the blog.

Previous                                                    Home                                                                            Next

Reference posts:

Monday, 24 July 2023

Java 8 Stream API Coding Interview Questions and Answers

      Before attending a Java interview, it's important to practice Stream API coding questions, as the Stream API is one of the most frequently asked topics in Java 8 interviews.

Below are some commonly asked Java 8 Stream API coding questions and their answers..

1) Write a program to print the list of elements from a list using java 8 stream

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
              List<String> list = Arrays.asList(new String[] {"ABC", "BCD", "CDE"});
	      list.stream().forEach(s -> System.out.println(s));
	}
}

Output:- ABC
              BCD
              CDE

2) Write a program to convert lowercase string element of a list into uppercase.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
     public static void main(String[] args) {
	   List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
	   list.stream().map(s-> s.toUpperCase()).forEach(
				s -> System.out.println(s));
     }
}

Output:- ABC
              BCD
              CDE

3) Print a list of strings those start with letter "A" and return updated list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Abc", "bcd", "cde"});
		List<String> updatedList = list.stream().filter(s-> s.startsWith("A"))
				.collect(Collectors.toList());
		updatedList.stream().forEach(s -> System.out.println(s));
	}
}

Output:- Abc

4) Write a code to calculate the summation of the integers from the list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1,2,3, 4,5});
		//Using lambda expression
		Integer sum = list.stream().mapToInt(i -> i).sum();
		System.out.println(sum);
		
		//Using Integer valueOf method
		Integer sumOfIntegers = list.stream().mapToInt(Integer::valueOf).sum();
		System.out.println(sumOfIntegers);
		
		//Using Integer intValue method
		Integer sumOfIntegerValue = list.stream().mapToInt(Integer::intValue).sum();
		System.out.println(sumOfIntegerValue);	
	}
}

Output:- 15
              15
              15

5) Create a Map object from List using Stream API

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<String> list = Arrays.asList(new String[] {"Ab", "Bcd", "Ce"});
		Map<String, Integer> map = list.stream().collect(Collectors.toMap(
				s->s, s->s.length()));
		map.forEach((x,v) -> System.out.println("key - "+x+", value - "+v));
	}
}

Output:-
key - Ab, value - 2
key - Ce, value - 2
key - Bcd, value - 3

6) Write a program to list the distinct integers from list or remove duplicates from the list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {1, 2, 1,4});
		List<Integer> listWithDistinct = list.stream().distinct().collect(Collectors.toList());
		listWithDistinct.stream().forEach(s-> System.out.println(s));
	}
}

Output:-1
             2
             4

7) Write a program to find the Minimum number from a Stream/list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer minNumber = list.stream().mapToInt(s->s).min().getAsInt();
	     System.out.println(minNumber);
	}
}

Output:-1

8) Write a program to find the Maximum number from a Stream/list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {1, 2,3,4});
	     Integer maxNumber = list.stream().mapToInt(s->s).max().getAsInt();
	     System.out.println(maxNumber);
	}
}

Output:-4

9) Write a program to sort the given list using java 8 stream.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());
	     sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-2
             3
             4
             8

10) Write a program to sort the given list in descending order using stream.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
		List<Integer> sortedList = list.stream().sorted(
				Collections.reverseOrder()).collect(Collectors.toList());
		sortedList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             4
             3
             2

11) Write a program to count the total number of integers in the list.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     long count = list.stream().count();
	     System.out.println(count);
	}
}

Output:-4

12)  Convert List<List<String>> into List<String> using flatMap method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<List<Integer>> listListOfStrings = new ArrayList<List<Integer>>();
	     List<Integer> list = Arrays.asList(new Integer[] {8, 2,3,4});
	     listListOfStrings.add(list);
	     //use flatMap method
	     List<Integer> newList = listListOfStrings.stream().flatMap(
				s-> s.stream()).collect(Collectors.toList());
	     newList.stream().forEach(s-> System.out.println(s));
	}
}

Output:-8
             2
             3
             4

13) Group by a list element and display the total count of the element using Collectors groupingBy method.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     Map<String, Long> mapWithLetterCount = letters.stream().collect(
	                        Collectors.groupingBy(
	                                Function.identity(), Collectors.counting()));  
	     System.out.println(mapWithLetterCount);   
	}
}

Output:- {A=2, B=1, C=2, D=2}

14)  Find the first element from the given list using java 8 stream.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C","A", "D", "C", "D");
	     String firstElement = letters.stream().findFirst().orElse("Default");  
	     System.out.println(firstElement);   
	}
}

Output:-A

15)  anyMatch code example - if any one of the list element matches with given character "A" then return true.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundElement = letters.stream().anyMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundElement);   
	}
}

Output:-true

16) allMatch code example - if all of the elements matches with the given element say "A" then return true else false.

import java.util.Arrays;
import java.util.List;

public class Java8Stream {
	public static void main(String[] args) {
             List<String> letters = Arrays.asList("A", "B", "C", "D");
	     boolean foundMatches = letters.stream().allMatch(s-> s.equalsIgnoreCase("A"));  
	     System.out.println(foundMatches);   
	}
}

Output:-false

17) Write a program to remove the duplicates from the list using Collectors toSet method.

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8Stream {
	public static void main(String[] args) {
	     List<String> letters = Arrays.asList("A", "B", "C", "D", "A", "B");
	     Set<String> nonDuplicateSet = letters.stream().collect(Collectors.toSet());  
	     nonDuplicateSet.stream().forEach(s-> System.out.println(s));
	}
}

Output:-A
             B
             C
             D

     
Thank you for reading the post.

Reference Posts:-

Wednesday, 19 July 2023

Difference Between map() and flatMap() in Java Streams

     The Stream API is one of the most important features introduced in Java 8. A stream is not a data structure, which means it does not store any data. It also does not modify the original data. Instead, it operates on a data source, such as a collection or an array, and processes the data in a convenient and efficient manner.

The Stream API helps you write cleaner, more readable, and more maintainable code while performing operations such as filtering, mapping, sorting, and reducing data.

Let's discuss the usage and differences between the map() and flatMap() methods.

  • Use the map() method when you want to transform each element of a stream into exactly one corresponding element. In other words, one input element is mapped to one output element.

  • Use the flatMap() method when the mapping function returns multiple values (such as a collection or another stream) for each input element, and you want to flatten all those values into a single stream.

map() method example:-

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMapExamples {
	
	public static void main(String[] args) {
		
		List<String> listOfStrings = Arrays.asList(new String[]{"abc", "bcd", "cde"});
		
		List<String> list = listOfStrings.stream()
				.map( s-> s.toUpperCase()).collect(Collectors.toList());
		
		list.stream().forEach(s-> System.out.println(s));
	}
	
}

the above code will print ABC, BCD and CDE.

flatMap() method example:-

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamflatMapExample {
	
	public static void main(String[] args) {
		
		List<List<String>> listListOfStrings = new ArrayList<List<String>>();
		listListOfStrings.add(Arrays.asList(new String[]{"ABC", "BCD"}));
		listListOfStrings.add(Arrays.asList(new String[]{"CDE", "DEF"}));
		
		List<String> listOfStrings = listListOfStrings.stream().flatMap(s->s.stream()).collect(Collectors.toList());
		
		listOfStrings.stream().forEach(s-> System.out.println(s));
	}

}

The flatMap() method converts a list of lists of strings into a single list of strings by flattening the nested collections into one stream. The above code prints the following values:

ABC, BCD, CDE, and DEF.

Saturday, 10 October 2020

Java Stream API: anyMatch(), allMatch(), and noneMatch() with Examples

          Java 8 introduced many powerful features, and the Stream API is one of the most important because it simplifies data processing and makes the code more concise and readable. In this post, we will explore the anyMatch(), allMatch(), and noneMatch() methods with examples.
  • anyMatch() – Returns true if at least one element in the stream matches the given predicate; otherwise, it returns false.

  • allMatch() – Returns true if all elements in the stream match the given predicate; otherwise, it returns false.

  • noneMatch() – Returns true if none of the elements in the stream match the given predicate; otherwise, it returns false.

Example:

package com.practice;

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

public class StreamMatchExample {

	public static void main(String[] args) {

		List<Employee> employeeList = new ArrayList<>();
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Sathish", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Pooja", "Female", "abc@gmail.com"));

		boolean allMatch = employeeList.stream().allMatch(
                               emp -> emp.getEmail().equalsIgnoreCase("abc@gmail.com"));
		System.out.println("allMatch - " + allMatch);

		boolean anyMatch = employeeList.stream().anyMatch(
                               emp -> emp.getName().equalsIgnoreCase("Mahesh"));
		System.out.println("anyMatch - " + anyMatch);

		boolean noneMatch = employeeList.stream().noneMatch(
                               emp -> emp.getName().equalsIgnoreCase("Anil"));
		System.out.println("noneMatch - " + noneMatch);
	}

}
 
Output :--
allMatch - true
anyMatch - true
noneMatch - true

Related Posts:-