1

I have this input String input = "TOM DICK HARRY";, I want output as "HARRY DICK TOM"

I have tried this (which I think is not an optimal way of doing)

public static void main(String[] args) {
    String input = "TOM DICK HARRY";

    String inputArr [] = input.split(" ");

    for (int i = inputArr.length; i >0; i--) {
        System.out.print(inputArr[i-1]+" ");    
    }

}

Is there any built in method to do this?

galath
  • 5,717
  • 10
  • 29
  • 41
paul
  • 4,333
  • 16
  • 71
  • 144
  • Unless you're doing this for an incredibly long string, what you have here is probably a good enough way of doing this. – Ownaginatious Sep 20 '15 at 07:31
  • What you have is fine. Why do you think it's not? In what way isn't it "optimum"? – JB Nizet Sep 20 '15 at 07:53
  • One can also use `ArrayUtils.reverse(inputArr); System.out.println(Arrays.toString(inputArr));` but then it would print square brackets in console like this: `[HARRY, DICK, TOM]`. So I found one more way not doing it optimum way. – paul Sep 20 '15 at 07:58

2 Answers2

0

Using Guava you can do:

Joiner.on(' ').join(Lists.reverse(Splitter.on(' ').splitToList("TOM DICK HARRY")));
Dzieciak
  • 83
  • 11
0

Using only vanilla Java 8:

public static void main(String[] args) {
    String input = "TOM DICK HARRY";

    List<String> list = Arrays.asList(input.split(" "));
    Collections.reverse(list);
    System.out.println(list.stream().collect(Collectors.joining(" ")));
}

It isn't necessarily "better" than your solution, but it uses standard API, which is what you seem to be after.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509