Convert string to list of strings in Java
If you want to convert any string into a list of characters using java you can use method split() with parameter - empty quotes:
String word = "Java rulez";
System.out.println(Arrays.asList(word.split("")));
result:
[J, a, v, a, , r, u, l, e, z]
Convert list of strings to string
If you want to do the reverse operation and the convert list into string then you can use method: String.join("",)
String word = "Java rulez";
List<String> list = Arrays.asList(word.split(""));
System.out.println(list);
String wordnew = String.join("", list);
System.out.println(wordnew);
result:
[J, a, v, a, , r, u, l, e, z]
Java rulez
Example using conversion string to list
Below you can find a program which show how to use conversion from string to list and the reverse in order to check if two words are anagrams:
public static void main(String[] args) {
System.out.println(isAnagram("face", "cafe"));
System.out.println(isAnagram("face", "caffe"));
}
public static Boolean isAnagram(String word1, String word2){
List<String> listWord1 = new ArrayList<>(Arrays.asList(word1.split("")));
List<String> listWord2 = new ArrayList<>(Arrays.asList(word2.split("")));
Collections.sort(listWord1);
Collections.sort(listWord2);
word1 = String.join("", listWord1);
word2 = String.join("", listWord2);
//return listWord1.equals(listWord2);
return word1.equals(word2);
//return word1 == word2 ; // not working because == tests for reference equality
}