Posts

Showing posts with the label Core Java

How to convert a List of Lists to a List in Java 8

In this section, we will show you how to convert a List<List<Object>> to a List<Object> in Java 8 using Stream API. Following ways can be used for converting  List<List<Object>> to a List<Object> :  1. By using flatMap () method  2. By using forEach () method 3. By using mapMult () method Example 1: Use flatMap () method Java 8 Stream flatMap () method is used to flatten a Stream of collections to a stream of objects. The objects are combined from all the collections in the original Stream. Flattening is referred to as merging multiple collections/arrays into one. import java.util.Arrays ; import java.util.Collections ; import java.util.List ; import java.util.stream.Collectors ; public class Main { // Driver code public static void main ( String [] args) { //Creating List of Lists List < List < String >> listOfLists = Collections . singletonList ( Arrays . asList ( &quo

How to generate random alphanumeric string of given size in Java

In this section, we will show you how to generate random alphanumeric string of given size in Java. Example 1: Use SecureRandom import java.security.SecureRandom ; public class Main { //Create a String of the characters which can be included in the string private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXY" + "Zabcdefghijklmnopqrstuvwxyz0123456789" ; // Driver code public static void main ( String [] args) { String randomAlphaNumericString = generateAlphaNumericString ( 25 ); System . out .println( randomAlphaNumericString ); } //Method to generate Random AlphaNumeric String public static String generateAlphaNumericString ( int length) { SecureRandom random = new SecureRandom(); StringBuilder builder = new StringBuilder(length); for ( int i = 0 ; i < length; i ++) { builder .append( ALPHA_NUMERIC_STRING .

How to convert a String to an int in Java

Image
In this section, we will show you how to convert a String to an int in Java.  Input : str = "3456"  Output : 3456 Input : str = "a3456e"  Output : 0 Input : str = "-3456"  Output : 3456 Following ways can be used for converting String to int: 1. By using Integer.parseInt() method 2. By using  NumberUtils.toInt method of Apache Commons library 3. By using  Ints::tryParse method of Guava library Example 1: Use Integer.parseInt() method Integer.parseInt() method parses the String argument as a signed decimal integer object. The characters in the string must be decimal digits, except that the first character of the string may be an ASCII minus sign '-' to indicate a negative value or an ASCII plus '+' sign to indicate a positive value. It returns the integer value which is represented by the argument in a decimal integer. public class Main { // Driver code public static void main ( String [] args) { //Example 1 S