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

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

问题描述

我在做我在哪里遍历集合简单的文本处理和打印报表时碰上这种情况下,有很多次,我想特别的情况下,最后一个元素(例如每正常的元素会被逗号分隔除了最后情况)。

有一些最佳实践成语或优雅的形式,不需要重复code,或者推搡在,其他人在回路中。

例如我有,我想在一个逗号分隔的列表来打印字符串列表。 (该做的,而解决方案已经假定列表中有2个或更多的元素,否则它会是一样坏的更正确与条件循环)。

例如。名单=(狗,猫,蝙蝠)

我要打印[狗,猫,蝙蝠]

我present 2方法


  1. 有关与条件循环

     公共静态字符串forLoopConditional(字符串[]项){
    字符串itemOutput =[;
    的for(int i = 0; I< items.length;我++){
        //检查是否我们在最后一个元素不是
        如果(ⅰ≤(items.length - 1)){
            itemOutput + =项[I] +,;
        }其他{
            //最后一个元素
            itemOutput + =项目[I]
        }
    }
    itemOutput + =];
    返回itemOutput;
     }


  2. 做while循环吸循环

     公共静态字符串doWhileLoopPrime(字符串[]项){
    字符串itemOutput =[;
    INT I = 0;
    itemOutput + =项目[我++];
    如果(ⅰ≤(items.length)){
        做{
            itemOutput + =,+项目[我++];
        }而(I< items.length);
    }
    itemOutput + =];
    返回itemOutput;
    }

    Tester类:

     公共静态无效的主要(字串[] args){
        的String []项目= {狗,猫,蝙蝠};

     的System.out.println(forLoopConditional(项目));
    的System.out.println(doWhileLoopPrime(项目));

    }


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

 公共字符串的toString(){
    迭代器< E> I =迭代器();
如果(!i.hasNext())
    返回[];StringBuilder的SB =新的StringBuilder();
sb.append('[');
为(;;){
    E E = i.next();
    sb.append(E ==本(这集):ΔE);
    如果(!i.hasNext())
    返回sb.append(']')的toString();
    sb.append(,);
}
}


解决方案

有很多在这些答案的循环,但我发现,一个Iterator和while循环更容易读取。例如:

 的Iterator<串GT; itemIterator = Arrays.asList(项目).iterator();
如果(itemIterator.hasNext()){
  //特殊情况第一项。在这种情况下,没有逗号
  而(itemIterator.hasNext()){
    //过程休息
  }
}

这是<一所采取的办法href=\"http://$c$c.google.com/p/google-collections/source/browse/trunk/src/com/google/common/base/Joiner.java#262\">Joiner在谷歌收藏和我觉得很可读。

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).

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

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).

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

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

I present 2 methods the

  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;
     }
    

  2. 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;
    }
    

    Tester class:

    public static void main(String[] args) {
        String[] items = { "dog", "cat", "bat" };
    
    
    

    System.out.println(forLoopConditional(items));
    System.out.println(doWhileLoopPrime(items));
    

    }

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(", ");
}
}

解决方案

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
  }
}

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

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

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