Java program to print the last unique character of a string [3 ways]

In this post, I will be sharing different ways to write a program to print the last unique character of a string in Java. But before moving forward, we will understand the question with the help of examples:

Input: "Alive is Awesome"
Output: m


Input: "Be in present"
Output: t


Read Also: Find the first unique character of a string in Java

Let's dive deep into the topic:

Print the last unique character of a String

1. Using indexOf() and lastIndexOf() methods [Easiest]


We will use the below algorithm to print the last unique character of a string in Java:

a. Scan the given string from end to start.

b. Call indexOf() and lastIndexOf() methods on the given string. indexOf() method in Java returns the position of the first occurrence of a given character in a string whereas lastIndexOf() method in Java returns the position of the last occurrence of a given character in a string.

Logic


If positions returned by the indexOf() and lastIndexOf() methods of the specified character are the same, then that character is the last non-repeated character in a string as shown below in the example:

public class LastUniqueCharacter {
    public static void main(String args[]) {
        String givenString = "Alive is Awesome";
        // Converting String to StringBuilder
        StringBuilder str = new StringBuilder(givenString);
        str = str.reverse();
        for(char ch : str.toString().toCharArray())
        {
            if(givenString.indexOf(ch) == givenString.lastIndexOf(ch))
            {
                System.out.println(ch);
                break;
            }
        }
    }
}


Output:
m

2. Using LinkedHashMap


We are going to use the below algorithm to find out the last unique character of a string in Java:

Logic


1. Count the occurrences of each character in the given string using LinkedHashMap.

2. Iterate through the Map and add all the characters whose occurrence is 1 to the ArrayList.

3. Print the last element of the ArrayList that represents the last unique character of a given string.

import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;

public class LastUniqueCharacter2 {
    public static void main(String args[]) {
        String givenString = "Be in present";
        List<Character> list = new ArrayList<>();
        Map<Character, Integer> map = new LinkedHashMap<>();
        for (char ch: givenString.toCharArray())
        {
            if(map.containsKey(ch))
            {
                map.put(ch, map.get(ch) + 1);
            }
            else
            {
                map.put(ch, 1);
            }
        }
        for(Map.Entry<Character, Integer> element: map.entrySet())
        {
            if((int)element.getValue() == 1)
                list.add(element.getKey());
        }
        System.out.println(list.get(list.size()-1));
    }
}


Output:
t

3. Using Java 8 Stream API


We can also use Java 8 Stream API to print the last unique character of a string as shown below in the example:

import java.util.Map;
import java.util.LinkedHashMap;

public class LastUniqueCharacter3 {
    public static void main(String args[]) {
        String givenString = "Love Yourself";
        Map<Character, Integer> map = new LinkedHashMap<>();
        for (char ch: givenString.toCharArray())
        {
            if(map.containsKey(ch))
            {
                map.put(ch, map.get(ch) + 1);
            }
            else
            {
                map.put(ch, 1);
            }
        }
        char ch = map.entrySet().stream().filter(x -> x.getValue() == 1).reduce((first, second) -> second).get().getKey();
        System.out.println(ch);
    }
}


Output:
f

That's all for today. Please mention in the comments if you know any other way of printing the last unique character of a string in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry