Java中是否有一个类可保留重复项,但不保留数据顺序?

Sri*_*man 4 java collections anagram

我正在处理字谜,所以我只关心字符串中存在的字符,而不关心它们的顺序。我没有找到合适的Collection类。

您能建议任何可以帮助我保留重复但忽略顺序的课程 吗?

Era*_*ran 8

您可以使用Map<Character,Integer>来计数的每个字符出现的次数String。如果Map为两个生成的Strings相等,则您将知道对应的Strings是字谜。

例如(此处使用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));
Run Code Online (Sandbox Code Playgroud)

输出:

Is anagram? true
Run Code Online (Sandbox Code Playgroud)