So I have this \"list\" of ints. It could be a Vector
, int[]
, List
, whatever.
My goal though is to sort the
I would rather skip doing another for loop.
That's silly. It's a silly desire and a silly basis for undertaking a code exercise. If you can better express the qualities that you want your code to have, then we've got something to talk about - that it should be easy to read, say, or performant, or testable, or robust. But "I'd rather skip it" just doesn't give us anything useful to work with.
How about something like this:
List<String> stringList = new ArrayList<String>();
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,1,2,11,3));
Collections.sort(list);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
stringList.add(iterator.next().toString());
}
System.out.println(stringList);
We can solve this problem using regular expression as follows:
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
String str = new String(Arrays.toString(intArray));
String stripNoneDigits= str.replaceAll("[^\\d]", "");
String[] stringArray = stripNoneDigits.split("");
Simple solution using Guava:
public List<String> toSortedStrings(List<Integer> ints) {
Collections.sort(ints);
return Lists.newArrayList(Iterables.transform(ints,
Functions.toStringFunction()));
}
Obviously, this solution (like any other) is going to use loops internally, but it gets it out of the code you have to read. You could also avoid changing the order in ints
by passing the result of Ordering.natural().sortedCopy(ints)
to transform
instead of using Collections.sort
first. Also, the Lists.newArrayList
part is not necessary if you don't need to be able to add new elements to the resulting list.
The shortened version of that method body, with static imports:
return transform(Ordering.natural().sortedCopy(ints), toStringFunction());
Using Functional Java,
import fj.data.List;
import static fj.data.List.*;
import static fj.pre.Show.*;
.
.
.
final List<Integer> xs = list(5,1,2,11,3);
final List<String> ys = xs.sort(Ord.intOrd).map(
new F<Integer, String>() {
@Override public String f(final Integer i) {
return String.valueOf(i);
}
}
);
listShow(stringShow).println(ys);
Using Eclipse Collections MutableIntList:
String[] result = IntLists.mutable.with(5, 1, 2, 11, 3)
.sortThis()
.collect(Integer::toString)
.toArray(new String[]{});
Assert.assertArrayEquals(
new String[]{"1", "2", "3", "5", "11"}, result);
Or trading some readability for potential efficiency:
MutableIntList intList = IntLists.mutable.with(5, 1, 2, 11, 3).sortThis();
String[] result = intList.injectIntoWithIndex(
new String[intList.size()],
(r, each, index) -> {
r[index] = Integer.toString(each);
return r;
});
Assert.assertArrayEquals(
new String[]{"1", "2", "3", "5", "11"}, result);
Note: I am a committer for Eclipse Collections