Java – Convert byte[] to int and vice versa

In Java, we can use ByteBuffer to convert int to byte[] and vice versa. int to byte[] int num = 1; // int need 4 bytes, default ByteOrder.BIG_ENDIAN byte[] result = ByteBuffer.allocate(4).putInt(number).array(); byte[] to int byte[] byteArray = new byte[] {00, 00, 00, 01}; int num = ByteBuffer.wrap(bytes).getInt(); 1. int to byte[] This Java example …

Read more

Java 8 – Convert Optional<String> to String

In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String. String result = list.stream() .filter(x -> x.length() == 1) .findFirst() // returns Optional .map(Object::toString) .orElse(""); Samples A standard Optional way to get a value. Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.List; import java.util.Optional; public class Java8Example1 { public static void main(String[] …

Read more

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long

Below example, the jdbcTemplate.queryForList returns an object of Integer and we try to convert it into a Long directly: public List<Customer> findAll() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) { Customer obj = new Customer(); obj.setID(((Long) row.get("ID"))); // the …

Read more

Java – Convert Integer to Long

In Java, we can use Long.valueOf() to convert an Integer to a Long TestInteger.java package com.mkyong.example; public class TestInteger { public static void main(String[] args) { Integer num = 1; System.out.println(num); // 1 Long numInLong = Long.valueOf(num); System.out.println(numInLong); // 1 } } References Long.valueOf JavaDocs)

Java – Convert String to double

In Java, we can use Double.parseDouble() to convert a String to double 1. Double.parseDouble() Example to convert a String 3.142 to an primitive double. String str = "3.142"; double pi = Double.parseDouble(str); System.out.println(pi); Output 3.142 2. Double.valueOf() Example to convert a String 3.142 to an Double object. String str = "3.142"; Double pi = Double.valueOf(str); …

Read more

Java – Convert Array to ArrayList

In Java, we can use new ArrayList(Arrays.asList(array)) to convert an Array into an ArrayList ArrayExample1.java package com.mkyong; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayExample1 { public static void main(String[] args) { String[] str = {"A", "B", "C"}; List<String> list = new ArrayList<>(Arrays.asList(str)); list.add("D"); list.forEach(x -> System.out.println(x)); } } Output A B C D …

Read more

Java – Convert Integer to String

In Java, you can use String.valueOf() to convert an Integer to String. 1. String.valueOf 1.1 Example to convert an Integer or int 10 to a String. Integer num = 10; //int num = 10; String numInString = String.valueOf(num); System.out.println(numInString); Output 10 2. toString() It works on Integer object only. Integer num = 10; String numInString …

Read more

Java – How to convert int to BigInteger?

In Java, we can use BigInteger.valueOf(int) to convert int to a BigInteger JavaExample.java package com.mkyong; import java.math.BigInteger; public class JavaExample { public static void main(String[] args) { int n = 100; System.out.println(n); // convert int to Integer Integer integer = Integer.valueOf(n); System.out.println(integer); // convert int to BigInteger BigInteger bigInteger = BigInteger.valueOf(n); System.out.println(bigInteger); // convert Integer …

Read more

Python – How to convert String to float

In Python, we can use float() to convert String to float. num = "3.1415" print(num) print(type(num)) # str pi = float(num) # convert str to float print(pi) print(type(pi)) # float Output 3.1415 <class ‘str’> 3.1415 <class ‘float’> References Python docs – float()

Python – How to convert int to String

In Python, we can use str() to convert a int to String. num1 = 100 print(type(num1)) # <class ‘int’> num2 = str(num1) print(type(num2)) # <class ‘str’> Output <class ‘int’> <class ‘str’> References Python docs – str() Python – How to convert String to int

Python – How to convert String to int

In Python, we can use int() to convert a String to int. # String num1 = "88" # <class ‘str’> print(type(num1)) # int num2 = int(num1) # <class ‘int’> print(type(num2)) 1. Example A Python example to add two numbers. 1.1 Add two String directly. num1 = "1" num2 = "2" num3 = num1 + num2 …

Read more

Python – How to convert float to String

In Python, we can use str() to convert float to String. pi = 3.1415 print(type(pi)) # float piInString = str(pi) # float -> str print(type(piInString)) # str Output <class ‘float’> <class ‘str’> References Python docs – str() Python – How to convert int to String Python – How to convert String to float

Java – How to add days to current date

This article shows you how to add days to the current date, using the classic java.util.Calendar and the new Java 8 date and time APIs. 1. Calendar.add Example to add 1 year, 1 month, 1 day, 1 hour, 1 minute and 1 second to the current date. DateExample.java package com.mkyong.time; import java.text.DateFormat; import java.text.SimpleDateFormat; import …

Read more

Java – Convert Object to Map example

In Java, you can use the Jackson library to convert a Java object into a Map easily. 1. Get Jackson pom.xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> 2. Convert Object to Map 2.1 A Jackson 2 example to convert a Student object into a java.util.Map Student.java package com.mkyong.examples; import java.util.List; public class Student { private String …

Read more

Java 8 – Convert Date to LocalDate and LocalDateTime

Here is the code to convert java.util.Date to java.time.LocalDate. Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // different way of create instant object LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); Convert java.util.Date to java.time.LocalDateTime. Date date = new Date(); LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); Convert java.util.Date to java.time.ZonedDateTime. Date date = new Date(); ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault()); …

Read more

Java 8 – Convert Instant to ZonedDateTime

Java 8 examples to show you how to convert from Instant to ZonedDateTime 1. Instant -> ZonedDateTime Example to convert a Instant UTC+0 to a Japan ZonedDateTime UTC+9 InstantZonedDateTime1.java package com.mkyong.date; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantZonedDateTime1 { public static void main(String[] argv) { // Z = UTC+0 Instant instant = Instant.now(); …

Read more

Java 8 – Convert Instant to LocalDateTime

Java 8 examples to show you how to convert from Instant to LocalDateTime 1. Instant -> LocalDateTime The java.time.LocalDateTime has no concept of time zone, just provide a zero offset UTC+0. InstantExample1.java package com.mkyong.date; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; public class InstantExample1 { public static void main(String[] argv) { // Parse a ISO 8601 …

Read more

Java 8 – How to convert String to LocalDate

Here are a few Java examples of converting a String to the new Java 8 Date API – java.time.LocalDate DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); String date = "16/08/2016"; //convert String to LocalDate LocalDate localDate = LocalDate.parse(date, formatter); The key is understand the DateTimeFormatter patterns Note You may interest at this classic java.util.Date example – How to …

Read more

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList Java8Example1.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example1 { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node"); //Convert a Stream to List List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output …

Read more

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

Java – Convert int[] to Integer[] example

Examples show you how to convert between int[] and its’ wrapper class Integer[]. 1. Convert int[] to Integer[] public static Integer[] toObject(int[] intArray) { Integer[] result = new Integer[intArray.length]; for (int i = 0; i < intArray.length; i++) { result[i] = Integer.valueOf(intArray[i]); } return result; } 2. Convert Integer[] to int[] public static int[] toPrimitive(Integer[] …

Read more

How to convert String to Date – Java

In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways. // String -> Date SimpleDateFormat.parse(String); // Date -> String SimpleDateFormat.format(date); Refer to table below for some of the common date and time …

Read more

Java MongoDB : Convert JSON data to DBObject

MongoDB comes with “com.mongodb.util.JSON” class to convert JSON data directly to a DBObject. For example, data represent in JSON format : { ‘name’ : ‘mkyong’, ‘age’ : 30 } To convert it to DBObject, you can code like this : DBObject dbObject = (DBObject) JSON.parse("{‘name’:’mkyong’, ‘age’:30}"); Example See a full example to convert above JSON …

Read more

How to convert negative number to positive in Java

To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this “number = (number < 0 ? -number : number);". See a complete example : package com.mkyong; public class app{ public static void main(String[] args) { int total = 1 + 1 + 1 + ...

Read more