ArrayList<Integer> factors = new ArrayList<Integer>()
factors = [1, 183, 3, 61];
Collections.sort(factors); is => [1, 3, 61, 183]
How can I turn [1, 3, 61, 183] to this => "1 3 61 183"
ArrayList<Integer> factors = new ArrayList<Integer>()
factors = [1, 183, 3, 61];
Collections.sort(factors); is => [1, 3, 61, 183]
How can I turn [1, 3, 61, 183] to this => "1 3 61 183"
Instead of using Collections.sort(factors) (or factors.sort(null)), you can use a Stream to sort and then collect it to String using Collectors.joining.
String result = factors.stream() // iterate all the list
.sorted() // make it sorted
.map(Number::toString) // convert Number to String
.collect(Collectors.joining(" ")); // collect them to String
The most confusing parts for you might be map and collect, let me explain more in detail:
map(Number::toString) is the same as map(n -> n.toString()) which calls toString method to each of the element iterated through. It results from Stream<String> in `Stream.collect(..) takes all the Stream as is and using a Collector creates an output from the streamed elements. It might be a Map, List or any object T - it depends on the Collector.Collectors.joining(" ") is a collector, that requires Stream<String> and concatenate elements together with the delimiter, which is one empty space in our case " ".The following code sample should accomplish this. We are declaring a new array to hold the string values (Setting it equal to the same size as the integer array), and filling out with the string values of the integers.
String myStringArray[] = new String[factors.length];
for (int i = 0; i < factors.length; i++){
myStringArray[i] = String.valueOf(intArray[i]);
System.out.println(Arrays.toString(myStringArray));
}//end for
You can use call toString of ArrayList and remove brackets like this,
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> factors = Arrays.asList(1, 183, 3, 61);
String arrayString = factors.toString();
System.out.println(arrayString.substring(1, arrayString.length() - 1).replace(",", ""));
}
}
You may convert any object to string directly using toString() method of that object.
here you can manipulate string functions as per your requirement.
replace brackets with double quotes as below
String s = factors.toString();
s=s.replace("[", "\"");
s=s.replace("]", "\"");
or you may only remove square brackets using substring mathod of string and make it useful. as below
String s = factors.toString();
s=s.substring(1,s.length()-1);
remove comma using below method
s=s.replace(",","");
try it , may it will help you.