What is the most elegant way to check if an arraylist contains one (and just one) value?
For example, how can I check if my arraylist
contains just zeroes:
[0,0,0,0]; [0,0,0,0,0]; [0,0,0,0,0,0,0,0]; <-- All should return true.
I know there are lots of ways to do this, including a very basic for-loop
but is there an elegant, possibly one-line solution that uses the standard API?
You could add the elements to a set, and check the size with something like this -
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");
}
}
Which will output All true
, unless you add a non zero value to any of the Integer[]
s.
Or, as a generic method
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;
}
It is true that these are less efficient then simply looping through the List
, like this -
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;
}
I would recommend the following:
public boolean isAllSame(ArrayList<?> list){
Object first=list.get(0);
for(int i=1;i<list.size();i++){
if(!list.get(i).equals(first))return false;
}
return true;
}
(Yes, it's a for loop. But, as was previously stated, it's not all that inelegant - runs in O(n) worst case and O(1) best. And only 4 lines.)
Put all array elements in a single arraylist and then put it in hashset and check size. If size is 1 then it will return/print true.
Set<Integer> val= new HashSet<Integer>();
List<Integer> allVal= new ArrayList<Integer>();
allVal.addAll(Arrays.asList(new Integer[] { 0, 0, 0, 0 }));
allVal.addAll(Arrays.asList(new Integer[] { 0, 0, 0, 0,0 }));
allVal.addAll(Arrays.asList(new Integer[] { 0, 0, 0, 0,0, 0, 0, 0 }));
val.addAll(allVal);
if(val.size()==1)
System.out.println("All true");
else
System.out.println("More than 1 element present");
You can try this:
List<Integer> lst = Arrays.asList(new Integer[] { 0, 0, 0, 0 });
int temp = Integer.parseInt(lst.toString().replaceAll(", ", "").replaceAll("\\[", "").replaceAll("]", "").trim());
if(temp == 0) {
System.out.println("All zeros");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.