Convert a String to a set of characters. - Java java.util

Java examples for java.util:Set Creation

Description

Convert a String to a set of characters.

Demo Code


//package com.java2s;

import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        System.out.println(strToSet(str));
    }/*from  w w w .j a v a 2  s . c om*/

    /**
     * Convert a String to a set of characters.
     * @param str The string to convert
     * @return A set containing the characters in str. A empty set
     *    is returned if str is null.
     */
    public static Set<Character> strToSet(String str) {
        Set<Character> set;

        if (str == null)
            return new HashSet<Character>();
        set = new HashSet<Character>(str.length());
        for (int i = 0; i < str.length(); i++)
            set.add(str.charAt(i));
        return set;
    }
}

Related Tutorials