How do I sort strings based on their length?

You can sort strings based on their length using the sort method combined with a custom comparator. In the code snippet below we are going to use the Arrays.sort() method. We pass an array of string to the sort() method and also a lambda expression as the custom comparator.

Here is how you’d do it in Java:

package org.kodejava.util;

import java.util.Arrays;

public class SortStringsExample {
    public static void main(String[] args) {
        String[] strings = {"Hello", "World", "Java", "is", "beautiful"};

        // Sort the array based on string length
        Arrays.sort(strings, (a, b) -> a.length() - b.length());

        // Print the sorted array
        Arrays.stream(strings).forEach(System.out::println);
    }
}

In this example, an array of strings is sorted in increasing order of their lengths. If you want to sort them in descending order, you can change the comparator to (a, b) -> b.length() - a.length().

The output of the code snippet above is:

is
Java
Hello
World
beautiful

How do I convert Base64 string to image file?

In the previous example, How do I convert an image file to a Base64 string?, you’ve seen how to convert image file to base64 string.

In this example, you will see how you can convert a base64 string back into an image file. Below are examples of how to do this in Java, using the Java 8 native java.util.Base64 class.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ToImage {
    public static void main(String[] args) throws Exception {
        // this is your Base64 encoded string
        String base64String = "iVBORw0...";

        byte[] decodedBytes = Base64.getDecoder().decode(base64String);
        Files.write(Paths.get("/path/to/your/outputimage.png"), decodedBytes);
    }
}

Just replace “/path/to/your/outputimage.png” with the actual path where you want to save the image.

This code will decode the base64 string back into a byte array, and then it will write this byte array into an image file. Be careful with the format of the image (PNG, JPG, etc.) as the format of the output file should match the format of the original base64-encoded image.

How do I convert an image file to a Base64 string?

A Base64 string is a way of encoding binary data using 64 printable characters, which are the 26 uppercase letters of the English alphabet, the 26 lowercase letters of the English alphabet, the 10 numerical digits, and the “+” and “/” symbols. This makes a total of 64 distinct characters, hence the name “Base64”.

Base64 encoding is commonly used when there is a need to encode binary data, especially when that data needs to be stored and transferred over media that is designed to handle text.

The primary use case of this encoding is to allow binary data to be represented in a way that looks and acts as plain text. For example, embedded images in HTML (often as data URIs), and storing complex data in XML or JSON.

In Java, you can use the java.util.Base64 classes to convert an image file to a base64 String. You can use it to convert a JPG or a PNG image file, or basically any binary image files. Here is a simple example:

package org.kodejava.util;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class ImageToBase64 {
    public static void main(String[] args) throws Exception {
        String imagePath = "/Users/wayan/tmp/photo-placeholder.png";

        byte[] fileContent = Files.readAllBytes(Paths.get(imagePath));
        String encodedString = Base64.getEncoder().encodeToString(fileContent);

        if (encodedString.length() > 65535) {
            System.out.println("Encoded string is too large");
        } else {
            System.out.println(encodedString);
        }
    }
}

Here are the first 200 characters of the generated base64 string:

iVBORw0KGgoAAAANSUhEUgAAAGQAAAB2CAYAAAA+/DbEAAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQA...

The size of a base64-encoded string could be significantly larger than the original file. It’s not always the best way to handle large files or in cases where you’re sensitive to data usage. To check the size of the generated string using the length() method of the String class.

As you can see in the code snippet above, the application will print “Encoded string is too large” if the base64 string of the image is larger than 65535 characters. Otherwise, it will print the base64 string

To use a Base64 encoded string with an HTML <img> tag, you can use the src attribute and specify the data as follows:

<img src="data:image/png;base64,iVBORw0..." alt="Your image description">

In this line:

  • data: is the Data URI scheme specifier.
  • image/png is the media type. This can be image/jpeg, image/gif, or other image types.
  • base64 indicates that the data is base64 encoded.
  • iVBORw0... is where your base64 data begins. Replace iVBORw0... with your base64 string.

You should replace image/png with the actual type of your image and replace the iVBORw0... part with your full Base64 string.

This approach allows you to inline small images directly into your HTML, reducing the number of HTTP requests. However, you should note that if images are large, this can increase the size of your HTML document and slow down load times. It might be more appropriate to use external image files for larger images.

Note that Base64 is not an encryption or hashing method, and should not be used for password or security purposes. It is a binary-to-text encoding schemes that represent binary data in an ASCII string format. It’s designed to be easily transmitted and stored while ensuring that the data remains intact without modification during transport.

How do I sum object property using Stream API?

If you have a collection of objects and want to sum one of their properties using the Java Stream API, you need to use the map() function to convert each object into the value of its property and then use the reduce() function to sum all the values.

Here is an example where we have a Person class with age property, and we want to get the sum of ages for a list of Person objects:

package org.kodejava.basic;

public class Person {
    private final int age;

    // Constructor, getters, and setters...
    public Person(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }
}
package org.kodejava.basic;

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

public class PropertySumDemo {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person(20),
                new Person(30),
                new Person(40));

        int totalAge = people.stream()
                .mapToInt(Person::getAge)
                .sum();

        System.out.println(totalAge);  // Outputs: 90
    }
}

In this example, mapToInt(Person::getAge) converts each Person object in the people stream into an int representing their age. The sum() function then adds up these ages, resulting in the total age.

How do I convert java.util.TimeZone to java.time.ZoneId?

The following code snippet will show you how to convert the old java.util.TimeZone to java.time.ZoneId introduced in Java 8. In the first line of our main() method we get the default timezone using the TimeZone.getDefault() and convert it to ZoneId by calling the toZoneId() method. In the second example we create the TimeZone object by calling the getTimeZone() and pass the string of timezone id. To convert it to ZoneId we call the toZoneId() method.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class TimeZoneToZoneId {
    public static void main(String[] args) {
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        System.out.println("zoneId = " + zoneId);

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone("US/Pacific");
        ZoneId zoneIdUsPacific = timeZoneUsPacific.toZoneId();
        System.out.println("zoneIdUsPacific = " + zoneIdUsPacific);
    }
}

This snippet prints the following output:

zoneId = Asia/Shanghai
zoneIdUsPacific = US/Pacific

To convert the other way around you can do it like the following code snippet. Below we convert the ZoneId to TimeZone by using the TimeZone.getTimeZone() method and pass the ZoneId.systemDefault() which return the system default timezone. Or we can create ZoneId using the ZoneId.of() method and specify the timezone id and then pass it to the getTimeZone() method of the TimeZone class.

package org.kodejava.datetime;

import java.time.ZoneId;
import java.util.TimeZone;

public class ZoneIdToTimeZone {
    public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone(ZoneId.systemDefault());
        System.out.println("timeZone = " + timeZone.getDisplayName());

        TimeZone timeZoneUsPacific = TimeZone.getTimeZone(ZoneId.of("US/Pacific"));
        System.out.println("timeZoneUsPacific = " + timeZoneUsPacific.getDisplayName());
    }
}

And here are the output of the code snippet above:

timeZone = China Standard Time
timeZoneUsPacific = Pacific Standard Time