gpt4 book ai didi

java - 检查 ArrayList 是否包含除一个元素之外的任何内容

转载 作者:行者123 更新时间:2023-12-01 23:18:35 24 4
gpt4 key购买 nike

检查数组列表是否包含一个(且仅一个)值的最优雅的方法是什么?

例如,如何检查我的 arraylist 是否只包含零:

        [0,0,0,0]; [0,0,0,0,0]; [0,0,0,0,0,0,0,0]; <-- All should return true.

我知道有很多方法可以做到这一点,包括非常基本的 for 循环,但是有没有一种优雅的、可能是使用标准 API 的单行解决方案?

最佳答案

您可以将元素添加到集合中,并使用类似这样的方法检查大小 -

public static void main(String[] args) {
if (new java.util.HashSet<Integer>(
Arrays.asList(new Integer[] { 0, 0, 0, 0 }))
.size() == 1
&& new java.util.HashSet<Integer>(
Arrays.asList(new Integer[] { 0, 0, 0, 0,
0 })).size() == 1
&& new java.util.HashSet<Integer>(
Arrays.asList(new Integer[] { 0, 0, 0, 0,
0, 0, 0, 0 })).size() == 1) {
System.out.println("All true");
} else {
System.out.println("Not true");
}
}

这将输出All tr​​ue,除非您向任何Integer[]添加非零值。

或者,作为通用方法

public static <T> boolean oneValue(java.util.List<T> in) {
// A one-liner.
return (in == null) ? false : new java.util.HashSet<T>(in).size() == 1;
}

确实,这些方法比简单地循环遍历 List 效率要低,就像这样 -

public static <T> boolean oneValue(java.util.List<T> in) {
if (in == null)
return false;
T o = in.get(0);
for (int i = 1; i < in.size(); i++)
if (!in.get(i).equals(o))
return false;
return true;
}

关于java - 检查 ArrayList 是否包含除一个元素之外的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20865306/

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