Reverse string using Streams in Java 8

0

I would like to reverse the order of a text string using Java Java API Java 8.

This is what I have tried, but it does not make the investment.

import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ReversedStrings {

  public static String solution(String str) {
    final Comparator<String> compareTo = String::compareTo;
    return Stream.of(str).sorted(compareTo.reversed()).collect(Collectors.joining());
  }
}

If you need a unit test I share the unit test code I use with JUnit

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ReversedStringsTest {
  @Test
  public void sampleTests() {
    assertEquals("dlrow", ReversedStrings.solution("world"));
  }
}

Is there any way to invest a string using streams?

    
asked by Ruslan López 20.06.2018 в 03:10
source

2 answers

2

If it is possible to do it. I have used the chars () function that returns an intStream that contains every letter represented in ascii. Then each letter is converted to String and reduced by concatenating each letter to the beginning of the accumulator.

String str = "letras";
str.chars()
   .mapToObj(e -> String.valueOf((char)e)) //convierte cada letra a String
   .reduce((a, e)-> e.concat(a)) //concadena todo pero con el orden contrario
   .ifPresent(System.out::println);//esta linia solo imprime la palabra 
    
answered by 22.06.2018 / 15:57
source
1

I do not think there is a way to do it following the mantra of the Streams

A Stream has the task of expressing what to do for each element of an underlying collection, not how to iterate over it For this purpose, the Streams do not save status (first item).

That is going to be a problem if you want to revert the string using only Streams, since to revert it you will have to iterate and save the intermediate results in a temporary collection.

In my opinion, this is one of those cases in which it is better to use a classic collection than to do it with Streams, or use the classes designated for it.

So, how do I do it without Streams?

I would use StringBuilder , it allows you to work pipeline style, as the Streams, and is specifically designed to modify a String:

public static String solution(String str) {
    return new StringBuilder(str).reverse().toString();
}
    
answered by 20.06.2018 в 08:24