Java等价于PHP的implode(',',array_filter(array())) [英] Java equivalent of PHP's implode(',' , array_filter( array () ))

查看:372
本文介绍了Java等价于PHP的implode(',',array_filter(array()))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在PHP中使用这段代码

I often use this piece of code in PHP

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

它清除空字符串,并将它们与,"连接.如果仅剩一个,它不会添加多余的逗号.它不会在末尾添加逗号.如果不存在,则返回空字符串.

It clears empty strings and join them with a ",". If only one remains it doesn't add an extra unneeded comma. It doesn't add a comma at the end. If none remains it returns empty string.

因此我可以获得以下结果之一

Thus I can get one of the following results

""
"Street abc 14"
"Street abc 14, 00168"
"Street abc 14, 00168, Rome"

Java 无需添加外部库(为Android设计)的最佳Java实现(更少的代码)是什么?

What is the best Java implementation (less code) in Java without having to add external libraries (designing for Android)?

推荐答案

使用Java 8的更新版本(原始文章结尾)

如果您不需要过滤任何元素,就可以使用

Updated version using Java 8 (original at the end of post)

If you don't need to filter any elements you can use

  • String.join(" > ", new String[]{"foo", "bar"});
  • String.join(" > ", "foo", "bar");

  • String.join(" > ", Arrays.asList("foo", "bar"));
  • 从Java 8开始,我们可以使用StringJoiner(而不是最初使用的StringBulder)并简化我们的代码.
    另外,为了避免在每次matches(" *")调用中重新编译" *" regex,我们可以创建单独的Pattern,它将其编译版本保存在某个字段中,并在需要时使用它.

    Since Java 8 we can use StringJoiner (instead of originally used StringBulder) and simplify our code.
    Also to avoid recompiling " *" regex in each call of matches(" *") we can create separate Pattern which will hold its compiled version in some field and use it when needed.

    private static final Pattern SPACES_OR_EMPTY = Pattern.compile(" *");
    public static String implode(String separator, String... data) {
        StringJoiner sb = new StringJoiner(separator);
        for (String token : data) {
            if (!SPACES_OR_EMPTY.matcher(token).matches()) {
                sb.add(token);
            }
        }
        return sb.toString();
    }   
    


    使用流,我们的代码可以看起来像


    With streams our code can look like.

    private static final Predicate<String> IS_NOT_SPACES_ONLY = 
            Pattern.compile("^\\s*$").asPredicate().negate();
    
    public static String implode(String delimiter, String... data) {
        return Arrays.stream(data)
                .filter(IS_NOT_SPACES_ONLY)
                .collect(Collectors.joining(delimiter));
    }
    

    如果使用流,则可以filter个元素,其中Predicate个元素.在这种情况下,我们希望谓词接受不仅是空格的字符串-换句话说,字符串必须包含非空格字符.

    If we use streams we can filter elements which Predicate. In this case we want predicate to accept strings which are not only spaces - in other words string must contain non-whitespace character.

    我们可以从Pattern中创建这样的谓词.以这种方式创建的谓词将接受任何包含子字符串的字符串,这些子字符串可以包含正则表达式可以匹配的子字符串(因此,如果正则表达式将查找"\\S",则谓词将接受诸如"foo "" foo bar ""whatever"之类的字符串,但不接受" "" ").

    We can create such Predicate from Pattern. Predicate created this way will accept any strings which will contain substring which could be matched by regex (so if regex will look for "\\S" predicate will accept strings like "foo ", " foo bar ", "whatever", but will not accept " " nor " ").

    所以我们可以使用

    Pattern.compile("\\S").asPredicate();
    

    或者更具描述性的否定字符串,它们只能是空格或为空

    or possibly little more descriptive, negation of strings which are only spaces, or empty

    Pattern.compile("^\\s*$").asPredicate().negate();
    

    接下来,当filter将删除所有空的或仅包含空格的字符串时,我们可以collect其余元素.感谢Collectors.joining,我们可以决定使用哪个定界符.

    Next when filter will remove all empty, or containing only spaces Strings we can collect rest of elements. Thanks to Collectors.joining we can decide which delimiter to use.

    public static String implode(String separator, String... data) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length - 1; i++) {
        //data.length - 1 => to not add separator at the end
            if (!data[i].matches(" *")) {//empty string are ""; " "; "  "; and so on
                sb.append(data[i]);
                sb.append(separator);
            }
        }
        sb.append(data[data.length - 1].trim());
        return sb.toString();
    }
    

    您可以像使用它

    System.out.println(implode(", ", "ab", " ", "abs"));
    

    System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));
    

    输出ab, abs

    这篇关于Java等价于PHP的implode(',',array_filter(array()))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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