Pages

Showing posts with label Java Conversions. Show all posts
Showing posts with label Java Conversions. Show all posts

Friday, November 26, 2021

Java - Converting between List and Set (6 ways)

1. Overview

In this article, We'll learn how to convert between List and Set objects. First, start with the basic java API methods, JDK 8 and above.

Finally, we'll learn how to convert List to Set and Set to List using Guava and apache commons API's.

In the previous article, we have discussed the conversion between List and Map objects.

Java - Converting between List and Set (6 ways)

Sunday, November 7, 2021

Java String to Float & Float to String Examples

1. Overview

In this tutorial, We'll learn how to convert String to Float value and Float to String value in java programming.

This can be done in several ways by using simple java api methods and also using third party api methods.

Java String to Float & Float to String Examples


2. Java String to Float Conversion


Converting string to float is done in mainly three ways using following methods.

All of these methods works for negative values alos.

  • Float.parseFloat()
  • Float.valueOf()
  • Float(String) constructor

2.1 Java String to Float Using Float.parseFloat()


Float.parseFloat() method is a static method from Float class and parseFloat() method returns primitive float value.

Look at the below example.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample1 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		float floatValue1 = Float.parseFloat(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Float value : " + floatValue1);

		String floatValueInString2 = "123.45";

		float floatValue2 = Float.parseFloat(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Float value : " + floatValue2);
	}
}

Output
Float value in String : 789.123F
String to Float value : 789.123
Float value in String : 123.45
String to Float value : 123.45

String value can take the F value at the end of the string to denote the value is float. If F is present in the middle of the string or any other alphabet then it will throw NumberFormatException.

2.2 Java String to Float Using Float.valueOf()


Float.valueOf() method takes the String as input and returns Float wrapper instance.

Below is the example.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample2 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		Float floatValue1 = Float.valueOf(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Wrapper Float value : " + floatValue1);

		String floatValueInString2 = "123.45";

		Float floatValue2 = Float.valueOf(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Wrapper Float value : " + floatValue2);
	}
}

Output is same as above the section.

valueOf() method internally calls parseFloat() method.


2.3 Java String to Float Using Float Constructor


Float constructor takes argument type of String. But this way is deprecated and suggested to use parseFloat() method.

But using of constructor will produce the same results.
package com.javaprogramto.programs.strings.tofloat;

public class StringToFloatExample3 {

	public static void main(String[] args) {

		String floatValueInString1 = "789.123F";

		Float floatValue1 = new Float(floatValueInString1);

		System.out.println("Float value in String : " + floatValueInString1);
		System.out.println("String to Float value using constructor: " + floatValue1);

		String floatValueInString2 = "123.45";

		Float floatValue2 = new Float(floatValueInString2);

		System.out.println("Float value in String : " + floatValueInString2);
		System.out.println("String to Float value using constructor: " + floatValue2);
	}
}


3. Java Float To String Conversion


Next, Let us see how to convert the Float to String value.

Float to String conversions part is already discussed in detail here.

Complete example of float to string conversion with primitive and wrapper objects.
package com.javaprogramto.programs.strings.tofloat;

public class FloatToStringExample {

	public static void main(String[] args) {

		// example 1 - valueOf()
		float primitiveFloat1 = 456.78f;

		String floatInString = String.valueOf(primitiveFloat1);

		System.out.println("Pritive float value 1 : " + primitiveFloat1);
		System.out.println("Float to String 1 : " + floatInString);

		// example 2 - valueOf()

		Float primitiveFloat2 = 456.78F;

		String floatInString2 = String.valueOf(primitiveFloat2);

		System.out.println("Pritive float value 2 : " + primitiveFloat2);
		System.out.println("Float to String 2 : " + floatInString2);

		// Example 3 - toString()

		float primitiveFloat3 = new Float(12367.987);

		String floatInString3 = Float.toString(primitiveFloat3);

		System.out.println("Pritive float value 3 : " + primitiveFloat3);
		System.out.println("Float to String 3 : " + floatInString3);
	}
}


Output:
Pritive float value 1 : 456.78
Float to String 1 : 456.78
Pritive float value 2 : 456.78
Float to String 2 : 456.78
Pritive float value 3 : 12367.987
Float to String 3 : 12367.987

4. Conclusion


In this article, we've seen how to convert String to Float and vice versa with examples.

When a String cannot be converted successfully then java throws runtime NumberFormatException.

Additionally, you can use apache commons beans utils FloatConverter class to convert String to Float.


Friday, November 5, 2021

Java Convert String to Double Examples

1. Overview

In this article, We'll learn how to convert the String values into double values in java using various methods and what are the problem when the string is with the valid double value.

First, We'll explore the examples on the following methods in order.

  • Double.parseDouble(String)
  • Double.valueOf(String)
  • Double Constructor
  • With invalid double string values
Java Convert String to Double Examples


2. Using Double.parseDouble()


First, let us look at the simple method which is Double.parseDouble(). Double class has many static utility methods and parseDouble() is one of them.


parseDouble() takes the String argument as input and returns double value.
package com.javaprogramto.programs.strings.todouble;

public class StringToDoubleExample1 {

	public static void main(String[] args) {

		// double value in string format
		String to_double = "1234";

		double doubleValue = Double.parseDouble(to_double);

		System.out.println("String to Double value : " + doubleValue);

		to_double = "100d";

		doubleValue = Double.parseDouble(to_double);

		System.out.println("String to Double value with d in the string : " + doubleValue);

	}
}

Output:
String to Double value : 1234.0
String to Double value with d in the string : 100.0

In the double string only d character is allowed to represent the double. Other than d are not allowed.

3. Using Double.valueOf()


Double class another utility method valueOf() which also takes the String as argument and returns the double value. But the difference between Double parseDouble() and valueOf() is parseDouble() returns primitive double, other valueOf() returns Double wrapper instance.

valueOf() internally calls the parseDouble() method.

The below example generates the same output as above.
package com.javaprogramto.programs.strings.todouble;

public class StringToDoubleExample2 {

	public static void main(String[] args) {

		// double value in string format
		String to_double = "1234";

		Double doubleValue = Double.valueOf(to_double);

		System.out.println("String to Double value with valueOf() : " + doubleValue);

		to_double = "100d";

		doubleValue = Double.valueOf(to_double);

		System.out.println("String to Double value with d in the string using valueOf() : " + doubleValue);

	}
}

4. Using Double Constructor


String can be converted to double directly using the Double class constructor as below. But this way is deprecated. Use parseDouble() for primitive and valueOf() for Double object instead of Double constructor.
package com.javaprogramto.programs.strings.todouble;

public class StringToDoubleExample3 {

	public static void main(String[] args) {

		// double value in string format
		String to_double = "1234";

		Double doubleValue = new Double(to_double);

		System.out.println("String to Double value with Double constructor : " + doubleValue);

		to_double = "100d";

		doubleValue = new Double(to_double);

		System.out.println("String to Double value with d in the string using Double constructor : " + doubleValue);

	}
}

Output:
String to Double value with Double constructor : 1234.0
String to Double value with d in the string using Double constructor : 100.0

5. String with non integers


If the double string value has alphabets or non digits other than d then what will be the output.

Let us create the simple example program with abc.

Given the input as 1234abc and we are expecting to not to convert into double inappropriate values.
package com.javaprogramto.programs.strings.todouble;

public class StringToDoubleExample4 {

	public static void main(String[] args) {

		// double value in string format
		String to_double = "1234abc";

		Double doubleValue = Double.parseDouble(to_double);

		System.out.println("String to Double value with abc string : " + doubleValue);

	}
}

Output:

Let us run and see the what is the outcome.
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234abc"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.base/java.lang.Double.parseDouble(Double.java:549)
	at com.javaprogramto.programs.strings.todouble.StringToDoubleExample4.main(StringToDoubleExample4.java:10)

Double valueOf() and parseDouble() method expect the input string to be in valid form of double otherwise NumberFormatException is expected to be thrown.

6. Conclusion


In this tutorial, we've seen how to convert the String values into double values in java.

By using third party api apache commons beans utils DoubleConverter class, string can be converted into double.




Monday, November 23, 2020

How To Convert String to Date in Java 8

1. Overview


In this article, you'll be learning how to convert String to Date in Java 8 as well as with Java 8 new DateTime API.

String date conversion can be done by calling the parse() method of LocalDate, DateFormat and SimpleDateFormat classes.

LocalDate is introduced in java 8 enhancements.

DateFormat is an abstract class and direct subclass is SimpleDateFormat.

To convert a String to Date, first need to create the SimpleDateFormat or LocalDate object with the data format and next call parse() method to produce the date object with the contents of string date.

Java Convert String to Date (Java 8 LocalDate.parse() Examples)


First, let us write examples on string to date conversations with SimpleDateFormat classs and then next with DateFormat class.

At last, Finally with LocalDate class parse() method.

All of the following classes are used to define the date format of input string. Simply to create the date formats.

LocalDate
DateFormat
SimpleDateFormat

Note: In date format Captial M indicates month whereas lowercase m indicate minutes.

This will be asked in the interview or written test on How to Format Date to String in Java 8?

Saturday, July 25, 2020

Java 8 - Convert List to Map (Handling Duplicate Keys)

Convert List to Map in Java

1. Introduction


In this article, You'll explore and learn how to convert List to Map in Java 8. 

First, Let us convert List into Map.
Next, Convert List of user-defined(custom) objects to Map and handling with the duplicate keys.
Finally, Sort and collect the Map from List

Java 8 - Convert List to Map (Handling Duplicate Keys)

Wednesday, July 8, 2020

Array to List: Program to convert Array to List in Java 8

1. Introduction


In this tutorial, you will learn how to convert an Array to List in java.

An array is a group of same type variables that hold a common name. Array values are accessed by an index that starts from 0. Arrays can hold primitive types and objects based on how the array is defined. If the array is created to store the primitive values then these are stored in the contiguous memory locations whereas objects are stored in the heap memory.

Java.util.List is sub-interface to the Collection interface. List is intended to store the values based on the index and accessed through index only. But, duplicate values can be stored in the list. List interfaces implementations are AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector.

List objects are accessed through the iterator() and listiterator() methods.

Array to List: Program to convert Array to List in Java 8


Let us dive into our core article to convert Array to List and this can be done in the following 4 ways.

  • Native Generics Apparoach
  • Arrays.asList()
  • Collections.addAll
  • Java 8 Stream API - Arrays.stream().collect()
  • Java 8 Stream boxed() for primitive arrays


Read more on How to convert Sting to Arraylist using Arrays.asList().


Input 1 : Array -> {"java", "program", "to.com", "is a ", "java portal"}
Output 1 : List -> {"java", "program", "to.com", "is a ", "java portal"}

Input 2 : Array -> {10, 20, 30, 40, 50}
Output 2 : List -> {10, 20, 30, 40, 50}


All Examples :


 // 1. Example on Arrays.asList()
 List<T> outputList = Arrays.asList(array);

  // 2. Example on Collections.addAll()
  Collections.addAll(outputList, array);
 
  // 3. Example on Arrays.stream().collect()
  List<T> outputList = Arrays.stream(array).collect(Collectors.toList());
 
  // 4. Example on boxed() method for primitive int array
  List<Integer> outputList = Arrays.stream(array).boxed().collect(Collectors.toList());

2. Convert List to Array using Native Generic Approach


package com.javaprogramto.java8.arraytolist;

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

public class ArrayToListExample {

    public static void main(String[] args) {

        String[] intArray = {"10", "20", "30", "40", "50"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("COnverted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();
        for (T t : array) {

            outputList.add(t);

        }

        return outputList;
    }

}

Output:
Array : [10, 20, 30, 40, 50]
COnverted ArrayList : [10, 20, 30, 40, 50]

3. Convert List to Array Using Arrays.asList()


Arrays class has a utility static method asList() which takes an array as input and returns a list object with array values.

package com.javaprogramto.java8.arraytolist;

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

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

        String[] intArray = {"java", "program", "to.com", "is a ", "java portal"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();

        outputList = Arrays.asList(array);
        return outputList;
    }

}


Output:
Array : [java, program, to.com, is a , java portal]
Converted ArrayList : [java, program, to.com, is a , java portal]

4. Convert List to Array Using Collections.addAll()


Collections class has a utility static method addAll() which takes two parameters. The first argument is the Output List and the second argument is the array of values. This method converts the second argument array to List. It populates the values from array to the given output list.

package com.javaprogramto.java8.arraytolist;

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

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

// Example using Collections.addAll(outputList, array);

        String[] intArray = {"java", "program", "to.com", "is a ", "java portal"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();

        Collections.addAll(outputList, array);

        return outputList;
    }

}

Output:
Array : [java, program, to.com, is a , java portal]
Converted ArrayList : [java, program, to.com, is a , java portal]

5. Java 8 Convert Array to List using Arrays.stream().collect()


Java 8 Stream API has added with a stream() method in the Arrays class to provide arrays support to Streams.

First, Convert the array into Stream by using Arrays.stream()
Second, Convert Stream into list using Collectors.toList() method.
Finally, Collect the converted stream into list using stream.collect() method.


package com.javaprogramto.java8.arraytolist;

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

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

// Example using Collections.addAll(outputList, array);

        String[] intArray = {"java", "program", "to", "convert", "array to list"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

// convert array to stream
        Stream<T> stream = Arrays.stream(array);

// collecting converted stream into list
        List<T> outputList = stream.collect(Collectors.toList());

        return outputList;
    }

}


Output:
Array : [java, program, to, convert, array to list]
Converted ArrayList : [java, program, to, convert, array to list]

6. Java 8 Convert Primitive Array to List using boxed() method


Stream api is added with boxed() method to work with primitive collections such as int[], float[] and double[] arrays.

boxed() method converts primitive values to its wrapper objects.

package com.javaprogramto.java8.arraytolist;

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

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

// Example using stream.boxed()

        int[] intArray = {1, 2, 3, 4, 5, 6, 6};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<Integer> list = convertPrimitiveArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static List<Integer> convertPrimitiveArrayToList(int[] array) {

// convert int array to Integer stream with boxed() method
        Stream<Integer> stream = Arrays.stream(array).boxed();

// collecting converted stream into list
        List<Integer> outputList = stream.collect(Collectors.toList());

        return outputList;
    }

}
Output:
Array : [1, 2, 3, 4, 5, 6, 6]
Converted ArrayList : [1, 2, 3, 4, 5, 6, 6]

7. Conclusion


In this article, you've seen all possible ways in the Java traditional and java 8 stream api.

Tuesday, June 30, 2020

Convert Any primitive to String Using ValueOf() in Java 8 - int to String

1. Introduction


In this article, You'll learn how to convert any primitive value to a String. Let us see the examples to convert int, long, double, char, boolean, float, and char[] array to String objects.

All of these primitive conversions are done using the String API valueOf() method. valueOf() method is an overloaded method in String class and declared a static method.

Java String ValueOf() - Primitive to String


Convert Any primitive to String Using ValueOf() in Java 8 - int to String


Thursday, June 25, 2020

Java String toLowerCase​() Examples to convert string to lowercase

1. Introduction


In this article, You'll be learning how to convert each character in the string into a lower case.

This is very easy and can be done using String class toLowerCase() method which returns a new String after converting every character to the lowercase.

Java String toLowerCase​() Examples to convert string to lowercase


2. Java String toLowerCase​() Syntax


Below is the syntax from java api documentation.

public String toLowerCase​()
public String toLowerCase​(Locale locale)


This method does not take any argument but returns a new String with lowercase contents.

How to convert String to lowercase?

3. Java String toLowerCase​() Example - To convert String to Lowercase


package com.javaprogramto.w3schools.programs.string;

public class StringToLowercase {

    public static void main(String[] args) {

        String string = "HELLO WELCOME TO THE JAVAPROGRAMTO.COM";
        String lowercaseStr = string.toLowerCase();

        System.out.println("Lowercase converted string : "+lowercaseStr);
    }
}

Output:

Lowercase converted string : hello welcome to the javaprogramto.com

4. Java String toLowerCase​() Locale Examples


By default, toLowerCase() does conversion internally based on the default locale from the computer or server.

toLowerCase(Locale.getDefault());

I have set the default locale as English in my machine so conversion is done for this locale;

But, if you want to for different locale then use the toLowerCase(Locale locale) overloaded method instead of the toLowerCase() method.


package com.javaprogramto.w3schools.programs.string;

import java.util.Locale;

public class StringToLowercase {

    public static void main(String[] args) {

        Locale defaultLocale = Locale.getDefault();
        System.out.println("Default locale : "+defaultLocale);

        String string = "I am Now Using the different locales";

        Locale french = Locale.forLanguageTag("co-FR");

        System.out.println("french loale : "+french);
        String lowercaseStr = string.toLowerCase(french);

        System.out.println("Lowercase converted string in French : "+lowercaseStr);

        Locale chineesLocale = new Locale("zh", "CN");

        String chineeslowerCase = string.toLowerCase(chineesLocale);
        System.out.println("Chinees locale string : "+chineeslowerCase);

    }

}

Output:

Default locale : en_US

french loale : co_FR

Lowercase converted string in French : i am now using the different locales

Chinees locale string : i am now using the different locales

5. Java String toLowerCase​() Internal Implementation


public String toLowerCase() {
    return toLowerCase(Locale.getDefault());
}

public String toLowerCase(Locale locale) {
    return isLatin1() ? StringLatin1.toLowerCase(this, value, locale)
                      : StringUTF16.toLowerCase(this, value, locale);
}

6. Conclusion


In this article,  We've seen how to convert the string to lowercase with the default locale and with custom locale for specified country.

All examples showed are over GitHub.

Sunday, April 5, 2020

Java Program To Convert List to Array (java 8 + Guava)

1. Introduction


In this tutorial, We'll learn how to convert List to Array in java. We are going to show the example programs using List, java 8 and Guava API methods.

Java Program To Convert List to Array (java 8 + Guava)

Friday, January 10, 2020

How to convert InputStream to File in Java

1. Overview


In this tutorial, We'll learn how to convert or write an InputStream to a File.

This can be done in different ways as below.

A) Using plain Java
B) Using java 7 NIO package
C) Apache Commons IO library
D) Guava

How to convert InputStream to File in Java



Wednesday, January 8, 2020

Java Program To Convert A Primitive Array To A List

1. Overview

In this programming tutorial, You will learn how to convert any primitive type array to a List. Primitive types are int, float, double, byte, long.
By end of this article, you will be able to convert int[] array to List<Integer> and float[] array to List<Float> or any primitive array to any List implementation.

Example programs are shown in classic java and using java 8 streams.

Java Program To Convert A Primitive Array To A List


Sunday, December 29, 2019

Java 8 Stream mapToInt(ToIntFunction) Method Examples | Convert Stream to IntStream

1. Overview


In this java 8 Streams series, We'll learn today what is Stream API mapToInt() method and when to use this. This method is used to convert the Stream to IntStream. Let us see it's syntax and few examples on mapToInt() method. This is also part of intermediate operations such as map() and filter() methods.

Java 8 Stream mapToInt(ToIntFunction) Method Examples | Convert Stream to IntStream




Tuesday, December 17, 2019

Java Program to Convert Int to String (Best Way)

1. Overview


In this conversion series articles, we will learn today how to convert int to String in java. Previously, I explained converting String to Int in java.

We do not talk much about unnecessary things. Directly jumping into our topic.

int conversion into String can be done using following java builtin methods.

String.valueOf()
Integer.toString()
String.format() 
Using + operator

Java Program to Convert Int to String


Wednesday, December 4, 2019

Java Program To Convert String to ArrayList Using Arrays.asList()

1. Overview


In this ArrayList articles series, You'll be learning today how to convert a String into an ArrayList using java built-in methods. There are many scenarios in the real-time applications where we need to do transform the string into a list of objects. Typically string should be multiple values separated by a delimiter. For example take a String like "Started,Approved,In Progress,Completed". Here we are seeing the statues in string format and all these statuses are for processing the tickets raised by the users. This is the status flow. We need to now convert this string into a List<String>.


Java Program To Convert String to ArrayList Using Arrays.asList()


Note: String can have integers, double and strings values with a delimiter. The same below shown program works for any type of values present in the input string.