Remove duplicate values from a string in java(从java中的字符串中删除重复值)
本文介绍了从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()把数组变成ListLinkedHashSet保留唯一性和插入顺序 - 它完成了为我们提供唯一值的所有工作,这些值通过构造函数传递- List 的
toString()是[element1, element2, ...] - 最后的
replace命令从toString() 中删除标点符号"
split("-")gives us the different values as an arrayArrays.asList()turns the array into a ListLinkedHashSetpreserves 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
replacecommands remove the "punctuation" from thetoString()
此解决方案要求值不包含字符序列 ", " - 对此类简洁代码的合理要求.
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中的字符串中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:从java中的字符串中删除重复值
基础教程推荐
猜你喜欢
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
