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

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

问题描述

任何人都可以让我知道如何从

Can anyone please let me know how to remove duplicate values from

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

请注意,订单被保留:)

Notice that the order is preserved :)

要点是:


  • split ( - )为数组提供不同的值

  • Arrays.asList()将数组转换成列表

  • LinkedHashSet 保留唯一性插入顺序 - 它执行所有的工作我们唯一的值,它们通过构造函数

  • 列表中的 toString()传递元素1,元素2,...]

  • 最终替换命令从 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("-"));
}



正则表达式更新!



如果你不在乎保存顺序(也就是删除重复的第一个事件就可以了):

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

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

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