用于特殊外壳最后一个元素的最佳循环习语 [英] Best Loop Idiom for special casing the last element

查看:21
本文介绍了用于特殊外壳最后一个元素的最佳循环习语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行简单的文本处理和打印语句时,我多次遇到这种情况,在这些语句中我循环遍历一个集合,并且我想对最后一个元素进行特殊处理(例如,除了最后一个元素之外,每个普通元素都将用逗号分隔案例).

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (for example every normal element will be comma separated except for the last case).

是否有一些最佳实践习惯用法或优雅的形式,不需要重复代码或在 if, else 循环中推入.

Is there some best practice idiom or elegant form that doesn't require duplicating code or shoving in an if, else in the loop.

例如,我有一个字符串列表,我想在逗号分隔列表中打印这些字符串.(do while 解决方案已经假设列表有 2 个或更多元素,否则它会与更正确的带条件的 for 循环一样糟糕).

For example I have a list of strings that I want to print in a comma separated list. (the do while solution already assumes the list has 2 or more elements otherwise it'd be just as bad as the more correct for loop with conditional).

例如List = ("dog", "cat", "bat")

e.g. List = ("dog", "cat", "bat")

我想打印[狗、猫、蝙蝠]"

I want to print "[dog, cat, bat]"

我介绍了两种方法

  1. 带条件的For循环

  1. For loop with conditional

public static String forLoopConditional(String[] items) {

String itemOutput = "[";

for (int i = 0; i < items.length; i++) {
    // Check if we're not at the last element
    if (i < (items.length - 1)) {
        itemOutput += items[i] + ", ";
    } else {
        // last element
        itemOutput += items[i];
    }
}
itemOutput += "]";

return itemOutput;
 }

  • do while 循环启动循环

  • do while loop priming the loop

    public static String doWhileLoopPrime(String[] items) {
    String itemOutput = "[";
    int i = 0;
    
    itemOutput += items[i++];
    if (i < (items.length)) {
        do {
            itemOutput += ", " + items[i++];
        } while (i < items.length);
    }
    itemOutput += "]";
    
    return itemOutput;
    }
    

    测试类:

    public static void main(String[] args) {
        String[] items = { "dog", "cat", "bat" };
    
        System.out.println(forLoopConditional(items));
        System.out.println(doWhileLoopPrime(items));
    
    }
    

  • 在 Java AbstractCollection 类中,它具有以下实现(有点冗长,因为它包含所有边缘情况错误检查,但还不错).

    In the Java AbstractCollection class it has the following implementation (a little verbose because it contains all edge case error checking, but not bad).

    public String toString() {
        Iterator<E> i = iterator();
    if (! i.hasNext())
        return "[]";
    
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = i.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! i.hasNext())
        return sb.append(']').toString();
        sb.append(", ");
    }
    }
    

    推荐答案

    这些答案中有很多 for 循环,但我发现 Iterator 和 while 循环更容易读取.例如:

    There are a lot of for loops in these answers, but I find that an Iterator and while loop reads much more easily. E.g.:

    Iterator<String> itemIterator = Arrays.asList(items).iterator();
    if (itemIterator.hasNext()) {
      // special-case first item.  in this case, no comma
      while (itemIterator.hasNext()) {
        // process the rest
      }
    }
    

    这是Joiner 在 Google 收藏中,我觉得它非常易读.

    This is the approach taken by Joiner in Google collections and I find it very readable.

    这篇关于用于特殊外壳最后一个元素的最佳循环习语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆