gpt4 book ai didi

java - 如何相互检查两个字符串列表?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:11 26 4
gpt4 key购买 nike

在 OOP Java 中上课,由于我对这门语言完全陌生,而且还不知道它必须提供的许多工具,我发现自己在黑暗中摸索着解决简单问题的方法,我可以对这些问题进行硬编码,但是我觉得使用 java.util 可以更简单地完成此操作。

假设我有一个字符串列表

String[] stringOne = {"a","b","c", "potato"};
String[] stringTwo = {"potato", "13"};

如何检查 stringTwo 中的任何给定项目在 stringOne 中出现了多少次?或相反亦然。我宁愿每次遇到这个问题时都不要双循环(或制作双循环方法)。

现在我使用 Collections.frequency() 并且只循环一次但有更简单的方法吗?谢谢。

最佳答案

Assume I have a list of strings

String[] stringOne = {"a","b","c", "potato"};
String[] stringTwo = {"potato", "13"};

这些是“数组”,而不是“列表”。 Arrays.asList(stringOne)stringOne 引用的数组的列表包装器。

How do I check how many times any given item in stringTwo occurs in stringOne?

new HashSet(Arrays.asList(stringOne)).retainAll(Arrays.asList(stringTwo))

将为您提供两者中的元素集。

Bag 类似的方法而不是一组会让你计数。

retainAll(Collection coll)

Remove any members of the bag that are not in the given collection, respecting cardinality. That is, if the given collection coll contains n copies of a given object and the bag has m > n copies, then delete m - n copies from the bag. In addition, if e is an object in the bag but !coll.contains(e), then remove e and any of its copies.

集合类中使用的等价概念是由 Object.equals(object) 定义的,java.lang.String 覆盖以按字典顺序进行比较。

如果您需要返回数组中的结果,请尝试 myBag.toArray(new String[0]) 将内容转储到字符串中。该参数在文档中进行了解释,但简而言之,它是一种类型提示,可以解决 Java 损坏的数组差异。

关于java - 如何相互检查两个字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14694285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com