从java中的字符串中删除重复值

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() 把数组变成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中的字符串中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)