从java中的字符串中删除重复值 [英] Remove duplicate values from a string in java

查看:43
本文介绍了从java中的字符串中删除重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何从

String s="Bangalore-Chennai-NewYork-Bangalore-Chennai"; 

输出应该是这样的

String s="Bangalore-Chennai-NewYork-";

使用 Java..

任何帮助将不胜感激.

推荐答案

这一行就搞定了:

public String deDup(String s) {
    return new LinkedHashSet<String>(Arrays.asList(s.split("-"))).toString().replaceAll("(^\[|\]$)", "").replace(", ", "-");
}

public static void main(String[] args) {
    System.out.println(deDup("Bangalore-Chennai-NewYork-Bangalore-Chennai"));
}

输出:

Bangalore-Chennai-NewYork

请注意订单被保留:)

重点是:

  • split("-") 将不同的值作为数组提供给我们
  • Arrays.asList() 把数组变成List
  • LinkedHashSet 保留唯一性插入顺序 - 它完成了为我们提供唯一值的所有工作,这些值通过构造函数传递
  • List 的 toString()[element1, element2, ...]
  • 最后的 replace 命令从 toString()
  • 中删除标点符号"
  • split("-") gives us the different values as an array
  • Arrays.asList() turns the array into a List
  • LinkedHashSet preserves uniqueness and insertion order - it does all the work of giving us the unique values, which are passed via the constructor
  • the toString() of a List is [element1, element2, ...]
  • the final replace commands remove the "punctuation" from the toString()

此解决方案要求值不包含字符序列 ", " - 对此类简洁代码的合理要求.

This solution requires the values to not contain the character sequence ", " - a reasonable requirement for such terse code.

当然是1行:

public String deDup(String s) {
    return Arrays.stream(s.split("-")).distinct().collect(Collectors.joining("-"));
}

正则表达式更新!

如果您不关心保留顺序(即可以删除 first 出现的重复项):

public String deDup(String s) {
    return s.replaceAll("(\b\w+\b)-(?=.*\b\1\b)", "");
}

这篇关于从java中的字符串中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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