I want to move every value greater than 0 to one decimal place for Collection<Double>
, how would I do that?
Where single units are moved 3 decimal places, tens are moved 2 decimal places and hundreds are moved 1 decimal place.
For example:
//an array like this
[140, 23, 3]
//should be
[0.140, 0.023, 0.003]
The script I am using counts the amount of times a particular String appears, though I'm unsure how to approach the above with Collection<Double>
:
public class doubleTest {
HashMap<String, Double> texted(String tex) {
HashMap<String, Double> counts = new HashMap<String, Double>();
for (String word : tex.split(" ")) { // loops through each word of the string
// text.split(" ") returns an array, with all the parts of the string between your regexes
// if current word is not already in the map, add it to the map.
if (!counts.containsKey(word)) counts.put(word, (double) 0);
counts.put(word,counts.get(word) + 1); // adds one to the count of the current word
}
return counts;
}
}
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
textSplit countWords = new textSplit();
HashMap<String, Double> result = countWords.texted(text);
Collection<Double> resultD = result.values();
for(int i = 0; i<resultD.size();i++){
double[] value = new double[]{i*0.001};
Collection<Double> valuet = Arrays.stream(value).boxed().collect(Collectors.toCollection(ArrayList::new));
System.out.println(valuet);
//output
//[0.0]
//[0.001]
//[0.002]
}
//System.out.println(resultD);
}
}
The simpler way of doing this is using the map() function.
Logic:- Multipy each element of array with 0.001
public class Test2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(140,23,3);
Collection<Double> collection;
collection = list.stream().map(x -> x* .001).collect(Collectors.toCollection(ArrayList::new));
System.out.println(collection);
}
}
Output
[0.14, 0.023, 0.003]