Java:以相反的顺序从List <string>连接String

时间:2019-01-26 02:05:40

标签: java string arraylist reverse

我有List<String> list = Arrays.asList("A", "B", "C");
我想以相反的顺序用定界符,连接列表中的所有字符串:

//result
String joinedString = "C,B,A";

实现此目标的最佳方法是什么?
目前我使用索引循环:

String joinedString = "";
List<String> list = Arrays.asList("A", "B", "C");
for (int i = list.size() - 1; i >= 0; i--) {
     String string = list.get(i);
     joinedString = joinedString + string + ",";
}
//to remove ',' from the last string
if(joinedString.length() > 0) {
    joinedString = joinedString.substring(0, joinedString.length() - 1);
}

//Output    
C,B,A

7 个答案:

答案 0 :(得分:4)

如果您不想通过调用列表上的Collections.reverse(List<?> list)来修改列表,请反向迭代该列表。

如果您不知道列表类型,请使用ListIterator向后迭代列表,而不会降低性能,例如否则,在i = 0; i < size()上进行常规的LinkedList循环会导致效果不佳。

要加入用逗号分隔的值,请使用StringJoiner(Java 8 +)。

List<String> list = Arrays.asList("A", "B", "C");

StringJoiner joiner = new StringJoiner(",");
for (ListIterator<String> iter = list.listIterator(list.size()); iter.hasPrevious(); )
    joiner.add(iter.previous());
String result = joiner.toString();

System.out.println(result); // print: C,B,A

答案 1 :(得分:2)

最简单的方法是使用Collections#reverseString#join

List<String> list = Arrays.asList("A", "B", "C");
Collections.reverse(list);
String joinedString = String.join(",", list);

答案 2 :(得分:1)

使用供应商

let $result;

if (true) {

   if (true) {
      $result = 'output 2';
   } else {
      $result = 'output 3';
}
   $result = 'output 1';
}

return `${result}`;

或插入了while循环

List<String> list = Arrays.asList("A", "B", "C");
int i[] = { list.size() };
Supplier<String> supplier = () -> (i[0] > 0) ? list.get(--i[0]) : null;
String s, reverse = "";
while ((s = supplier.get()) != null) {
        reverse +=","+s;
}
reverse = (reverse.length() > 0) ? reverse = reverse.substring(1): "" ;

答案 3 :(得分:1)

可能是有用的类似连接的收集器:

    public static Collector<CharSequence, ?, String> joiningReversed(CharSequence delimiter, CharSequence prefix, CharSequence suffix) {
    return Collector.of(StringBuilder::new,
            (sb, item) -> {
                if (sb.length() != 0) {
                    sb.insert(0, delimiter);
                }
                sb.insert(0, item);
            },
            (a, b) -> {
                throw new UnsupportedOperationException();
            },
            sb -> sb.insert(0, prefix).append(suffix).toString());
    }

并在流中使用它:

    List<String> list = Arrays.asList("A", "B", "C");
    String result = list.stream()
                .collect(joiningReversed(",", "", ""));
    System.out.println(result);

答案 4 :(得分:0)

使用比较器的另一种方法。

List<String> list = Arrays.asList("A", "B", "C");
list.sort(Comparator.reverseOrder());
String joinedString = String.join(",", list);

答案 5 :(得分:0)

一种方法使用StringBuilder

    StringBuilder sb = new StringBuilder();
    List<String> strs = Arrays.asList("A", "b", "c","d");
    for (int i = 0; i < strs.size(); i++) {
        sb.append(strs.get(i));
        if (i != strs.size() - 1) {
            sb.append(",");
        }
    }
    System.out.println(sb.reverse().toString());

答案 6 :(得分:0)

这是使用Java 8的一种解决方案:

Collections.reverse(list);

//res contains the desired string
String res = list.stream().collect(Collectors.joining(","));