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

前端 未结 9 1297
自闭症患者
自闭症患者 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:46

    You'd have to add your strings to an ArrayList, remove empty ones, and format it accordingly:

    public static String createAddressString( String street, String zip_code, String country) {
        List list = new ArrayList();
        list.add( street);
        list.add( zip_code);
        list.add( country);
    
        // Remove all empty values
        list.removeAll(Arrays.asList("", null));
    
        // If this list is empty, it only contained blank values
        if( list.isEmpty()) {
            return "";
        }
    
        // Format the ArrayList as a string, similar to implode
        StringBuilder builder = new StringBuilder();
        builder.append( list.remove(0));
    
        for( String s : list) {
            builder.append( ", ");
            builder.append( s);
        }
    
        return builder.toString();
    }
    

    Additionally, if you had String[], an array of strings, you can easily add them to an ArrayList:

    String[] s;
    List list = new ArrayList( Arrays.asList( s));
    

提交回复
热议问题