确定是否由Java 8中的anagram元素组成的列表 [英] Determine if a list composed of anagram elements in Java 8

查看:84
本文介绍了确定是否由Java 8中的anagram元素组成的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定列表是否是使用Java 8的字谜。

I want to determine if a list is anagram or not using Java 8.

示例输入:

"cat", "cta", "act", "atc", "tac", "tca"

我写了以下函数来完成这项工作,但我想知道是否有更好更优雅的方法来做到这一点。

I have written the following function that does the job but I am wondering if there is a better and elegant way to do this.

boolean isAnagram(String[] list) {
    long count = Stream.of(list)
            .map(String::toCharArray)
            .map(arr -> {
                Arrays.sort(arr);
                return arr;
            })
            .map(String::valueOf)
            .distinct()
            .count();
    return count == 1;

}

似乎我无法用<$排序char数组c $ c> Stream.sorted()方法,这就是我使用第二个map运算符的原因。如果有一些方法我可以直接在char流而不是Stream of char数组上操作,那也会有所帮助。

It seems I can't sort char array with Stream.sorted() method so that's why I used a second map operator. If there is some way that I can operate directly on char stream instead of Stream of char array, that would also help.

推荐答案

而不是创建和排序 char [] int [] ,这不能内联,因此中断 你可以在字符串中获得字符中的字符,并在将它们转换为数组之前对它们进行排序。请注意,这是 IntSteam ,而 String.valueOf(int [])将包含数组的内存地址,这在这里不是很有用,所以在这种情况下最好使用 Arrays.toString

Instead of creating and sorting a char[] or int[], which can not be done inline and thus "breaks" the stream, you could get a Stream of the chars in the Strings and sort those before converting them to arrays. Note that this is an IntSteam, though, and String.valueOf(int[]) will include the array's memory address, which is not very useful here, so better use Arrays.toString in this case.

boolean anagrams = Stream.of(words)
        .map(String::chars).map(IntStream::sorted)
        .map(IntStream::toArray).map(Arrays::toString)
        .distinct().count() == 1;

当然,你也可以使用 map(s - > Arrays。 toString(s.chars()。sorted()。toArray()))而不是四个地图的系列。不确定速度是否存在(显着)差异,这可能主要是品味问题。

Of course, you can also use map(s -> Arrays.toString(s.chars().sorted().toArray())) instead of the series of four maps. Not sure if there's a (significant) difference in speed, it's probably mainly a matter of taste.

此外,您可以使用 IntBuffer.wrap 使数组具有可比性,这应该比 Arrays.toString 快得多(感谢 Holger

Also, you could use IntBuffer.wrap to make the arrays comparable, which should be considerably faster than Arrays.toString (thanks to Holger in comments).

boolean anagrams = Stream.of(words)
        .map(s -> IntBuffer.wrap(s.chars().sorted().toArray()))
        .distinct().count() == 1;

这篇关于确定是否由Java 8中的anagram元素组成的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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