我正在处理字谜,所以我只关心字符串中出现的字符,而不关心它们的顺序。 我搜索了一个合适的 Collection 类,但没有成功。
你能推荐任何可以帮助我的类(class)吗 保留重复项但忽略顺序?
最佳答案
您可以使用 Map<Character,Integer>
计算 String
的每个字符出现的次数.如果Map
为两个 String
生成s是相等的,你就会知道对应的String
s 是字谜。
例如(这里我使用了Map<Integer,Long>
而不是Map<Character,Integer>
因为它更方便):
String one = "animal";
String two = "manila";
Map<Integer,Long> mapOne = one.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Map<Integer,Long> mapTwo = two.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println ("Is anagram? " + mapOne.equals(mapTwo));
输出:
Is anagram? true
关于java - Java中是否有一个类保留重复项但不保留数据顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58201191/