Java equivalent of PHP's implode(',' , array_filter( array () ))

前端 未结 9 1221
自闭症患者
自闭症患者 2020-12-29 19:32

I often use this piece of code in PHP

$ordine[\'address\'] = implode(\', \', array_filter(array($cliente[\'cap\'], $cliente[\'citta\'], $cliente[\'provincia\'         


        
9条回答
  •  北海茫月
    2020-12-29 19:40

    Here's my implode implementation:

    /**
     * Implodes the specified items, gluing them using the specified glue replacing nulls with the specified
     * null placeholder.
     * @param glue              The text to use between the specified items.
     * @param nullPlaceholder   The placeholder to use for items that are null value.
     * @param items             The items to implode.
     * @return  A String containing the items in their order, separated by the specified glue.
     */
    public static final String implode(String glue, String nullPlaceholder, String ... items) {
        StringBuilder sb = new StringBuilder();
        for (String item : items) {
            if (item != null) {
                sb.append(item);
            } else {
                sb.append(nullPlaceholder);
            }
            sb.append(glue);
        }
        return sb.delete(sb.length() - glue.length(), sb.length()).toString();
    }
    

提交回复
热议问题