I have a HashSet<Double>
from which I want to extract those elements that are integers, ie those elements that have all zeros after the decimal. Is there a standard way of doing this? I could do something roundabout, eg: given a double x
, I can look at all the values after the decimal and see if they are all zero, but this seems convoluted.
you can cast them into integer and equalize the casted value to the original
double d = 1.5;
if((int)d==d) // integer
else // not integer
You can do something like this:
HashSet<Double> hd = new HashSet<> ();
hd.add (3.5);
hd.add (2.0);
hd.add (3.444);
hd.add (-1.0);
Set<Double> filtered = hd.stream()
.filter (x -> (int)(double)x == x)
.collect (Collectors.toSet());
System.out.println (filtered);
Output:
[2.0, -1.0]
You first have to cast the Double
to double
and then cast it to an int
. If that int
is equal to the original Double
, that Double
holds an integer value.
If you want to avoid the explicit casting, you can change
.filter (x -> (int)(double)x == x)
to
.filter (x -> x.intValue() == x)
which does the exact same thing.
I guess you like to have a final result of Integers and not of Doubles. Eg 7 and not 7.0.
So try this one:
Set<Double> set = new HashSet<>();
set.add(6.4);
set.add(10.44);
set.add(7.0);
Set<Integer> filtered = set.stream()
.filter(item -> Math.floor(item) == item)
.map(Double::intValue)
.collect(Collectors.toSet());
System.out.println(filtered);
Try this:
Collection<Integer> filterIntegers( final HashSet<Double> doubles )
{
final var retValue = doubles.stream()
.filter( d -> d.doubleValue() == d.intValue() )
.map( Double::intValue )
.collect( Collector.toSet() );
return retValue;
}
Explicitly comparing the real (double) value of d
with its integer value seems to me as the most precise implementation of the requirement. No casting around, no math operations involved (although all these will provide the same results.).
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.