从重复的值删除单个标识我有一个字符串值如下:在Java中
String id = "21713|4 Pieces=50,21701|2 pieces=35,21701|250 Gram=30,21701|250 Gram=30,21701|250 Gram=30,";
以上ID都21701|250 Gram=30
重复三次。我想要做的是,当我点击删除项目按钮,将通过没有。的计数,只有那么多的计数21701|250 Gram=30
应该被删除。
我们该如何处理?
从重复的值删除单个标识我有一个字符串值如下:在Java中
String id = "21713|4 Pieces=50,21701|2 pieces=35,21701|250 Gram=30,21701|250 Gram=30,21701|250 Gram=30,";
以上ID都21701|250 Gram=30
重复三次。我想要做的是,当我点击删除项目按钮,将通过没有。的计数,只有那么多的计数21701|250 Gram=30
应该被删除。
我们该如何处理?
我认为你拥有的最佳选择是将字符串解析为一个存储重复次数的Map。 使用此地图,您可以在按下按钮之后重建字符串。
限制:如果字符串部分的顺序很重要,您可能会遇到问题。
恕我直言,你的应用程序中有这样一个字符串开始似乎是不好的设计。 (除非是练习)
试试这个。
static String remove(String id, int countToRemove) {
Set<String> set = Stream.of(id.split("(?<=,)"))
.collect(Collectors.groupingBy(s -> s, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == countToRemove)
.map(e -> e.getKey())
.collect(Collectors.toSet());
return Stream.of(id.split("(?<=,)"))
.filter(s -> !set.contains(s))
.collect(Collectors.joining());
}
而且
String id = "21713|4 Pieces=50,21701|2 pieces=35,21701|250 Gram=30,21701|250 Gram=30,21701|250 Gram=30,";
System.out.println(remove(id, 3));
结果:
21713|4 Pieces=50,21701|2 pieces=35,
在java7
static String remove(String id, int countToRemove) {
Map<String, Integer> map = new HashMap<>();
for (String key : id.split("(?<=,)")) {
Integer value = map.get(key);
if (value == null)
value = 0;
map.put(key, value + 1);
}
Set<String> set = new HashSet<>();
for (Entry<String, Integer> e : map.entrySet())
if (e.getValue() == countToRemove)
set.add(e.getKey());
StringBuilder sb = new StringBuilder();
for (String key : id.split("(?<=,)"))
if (!set.contains(key))
sb.append(key);
return sb.toString();
}
让我们看看你已经尝试什么 – m0skit0