-7

Here is my code:

public void Calculate(){

   String name1="tsebo";
   String name2="mokoena";

   String sentance= name1.toLowerCase().trim()+" true love "+
            name2.toLowerCase().trim();
    String word=sentance.replaceAll(" ","").trim();
    List<String> original=Arrays.stream(word.split(""))
            .collect(Collectors.toList());
    
    System.out.print(original);
}

The output I get:

[, t, s, e, b, o, t, r, u, e, l, o, v, e, m, o, k, o, e, n, a]

The problem is the first empty char before "t". Help remove it.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 4
    `.split("")` is not recommended. Do you want an array of characters? then use `word.toCharArray()`. Or `word.chars()` if you want a `Stream` to continue working with it. – Clashsoft Aug 16 '21 at 22:41
  • 1
    Please read: [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – Turing85 Aug 16 '21 at 22:46
  • 1
    It works for me. What is your question? –  Aug 16 '21 at 23:03
  • @Clashsoft `.chars()` and `.toCharArray()` are not recommended. They split surrogate pairs. –  Aug 17 '21 at 00:19

1 Answers1

2

Cannot reproduce. Your code when copy-pasted works as you intended; no empty first element.


When working character-by-character, better to use Unicode code points. Each of the 143,859 characters defined in Unicode is assigned a number, called a code point, from zero to just over a million.

Get a IntStream of these integer code point numbers, in the form of a sequence of int primitive values.

IntStream codePointStream = "love".codePoints();

Capture those numbers to a list. Convert from primitive int to object Integer.

List < Integer > codePoints = codePointStream.boxed().toList();

codePoints.toString(): [108, 111, 118, 101, 128152]

Map those to a list of single-character String objects, to get back to the characters. Call Character.toString( codePoint ) to generate the text.

List < String > characters = codePoints.stream().map( Character :: toString ).toList();

characters = [l, o, v, e, ]

We could combine those.

List < String > characters =
        "love"
                .codePoints()
                .mapToObj( Character :: toString )
                .toList();

characters = [l, o, v, e, ]

Before Java 16, replace .toList() with the more verbose .collect( Collectors.toList() ).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • this's an excelent answer, but the question is asking for: `.collect( Collectors.joining(", ", "[", "]");` – bichoFlyer Aug 17 '21 at 02:30
  • @bichoFlyer Ahh, no it’s not. I have no idea what you are referring to. The Question is about generating a string representing a list of strings. No “joining”. – Basil Bourque Aug 17 '21 at 06:40