How to find hamming weight in java
Table of Content
How to find Hamming Weight in Java
1
.
For instance:
- 1001 → Hamming weight = 2
- 100001111 → Hamming weight = 5
Using Simple Division and Remainder
public static int hammingWeight(int n) {
int count = 0;
while (n != 0) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
return count;
}
Using Bit Masking
int
in Java has 32 bits, we shift a mask bit and check each position with a bitwise AND.
public static int hammingWeightII(int n) {
int count = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
count++;
}
mask = mask << 1; // shift the mask
}
return count;
}
Full Example
package ic.binary;
public class NumberOf1s {
public static void main(String[] args) {
int n = 5;
System.out.println("Number of 1 bits for " + n + " -> " + hammingWeight(n));
System.out.println("Number of 1 bits for " + n + " -> " + hammingWeightII(n));
n = 8;
System.out.println("Number of 1 bits for " + n + " -> " + hammingWeight(n));
System.out.println("Number of 1 bits for " + n + " -> " + hammingWeightII(n));
}
public static int hammingWeight(int n) {
int count = 0;
while (n != 0) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
return count;
}
public static int hammingWeightII(int n) {
int count = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) {
count++;
}
mask <<= 1;
}
return count;
}
}
Number of 1 bits for 5 -> 2
Number of 1 bits for 5 -> 2
Number of 1 bits for 8 -> 1
Number of 1 bits for 8 -> 1
Table of Content
Java OptionalInt example
OptionalInt
allows us to create an object which may or may not contain an int value.
If a value is present, isPresent()
will return true and getAsInt()
will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse()
.
Other classes similar to OptionalInt
are OptionalDouble
, OptionalLong
, and Optional
.
These help us eliminate exceptions that occur due to the absence of a value at runtime.
The key is to first check if the Optional contains a value before trying to retrieve it.
OptionalIntExample
In this example, we return an OptionalInt
from a Stream created from an integer array and finally return a value using the reduce()
method.
If the value is present, then only we print it using getAsInt()
.
package javaexp.blogspot.stream;
import java.util.Arrays;
import java.util.OptionalInt;
public class OptionalIntExample {
public static void main(String[] args) {
int iarray[] = {9, 10, 11, 12, 15, 15, 25};
OptionalInt result = Arrays.stream(iarray)
.reduce((left, right) -> left);
if (result.isPresent()) {
System.out.println("First element of Array: " + result.getAsInt());
}
}
}
Summary
OptionalInt
and other respective Optional classes help protect against
NullPointerException
when trying to retrieve values from potentially null objects.
They provide a safer way to work with values that may or may not be present.
Bucket sort implementation in Java
Table of Content
Bucket Sort in Java
What is Bucket Sort
function bucketSort(array, k) is
buckets ← new array of k empty lists
Max ← the maximum key value in the array
Min ← the minimum key value in the array
Divisor ← (Max - Min) / (k - 1)
for i = 0 to length(array) do
insert array[i] into buckets[floor((array[i] - Min) / Divisor)]
for i = 0 to k do
Sort(buckets[i])
return concatenation of buckets[0] ... buckets[k]
import java.util.*;
public class BucketSortExample {
public static void main(String[] args) {
int[] arr = {8, 4, 2, 10, 3, 1, 9, 6, 5, 7};
int numBuckets = 5;
bucketSort(arr, numBuckets);
System.out.println("Sorted array:");
for (int value : arr) {
System.out.print(value + " ");
}
}
public static void bucketSort(int[] arr, int numBuckets) {
if (numBuckets <= 0) return;
// create empty buckets
ArrayList> buckets = new ArrayList<>(numBuckets);
for (int i = 0; i < numBuckets; i++) {
buckets.add(new ArrayList<>());
}
distributeToBuckets(arr, numBuckets, buckets);
// sort each bucket
for (ArrayList bucket : buckets) {
Collections.sort(bucket);
}
// concatenate
int index = 0;
for (ArrayList bucket : buckets) {
for (int item : bucket) {
arr[index++] = item;
}
}
}
private static void distributeToBuckets(int[] arr, int numBuckets,
ArrayList> buckets) {
int min = Arrays.stream(arr).min().getAsInt();
int max = Arrays.stream(arr).max().getAsInt();
float diff = max - min;
float divisor = diff / (numBuckets - 1);
for (int value : arr) {
int index = (int) ((value - min) / divisor);
if (index >= numBuckets) index = numBuckets - 1; // safeguard
buckets.get(index).add(value);
}
}
}
Complexity
Best Case: O(n + k)
Average Case: O(n + k)
Worst Case: O(n²)
Space Complexity: O(n + k)
Summary
IntSummaryStatistics
Example
public class IntSummaryStatisticsExample {
public static void main(String[] args) {
Stream<Integer> numStream = Stream.of(1, 2, 3, 4, 5);
IntSummaryStatistics summary = numStream.mapToInt(p-> p).summaryStatistics();
System.out.println("Max From the Data is " + summary.getMax());
System.out.println("Min From the Data is " + summary.getMin());
System.out.println("Average From the Data is " + summary.getAverage());
System.out.println("Sum From the Data is " + summary.getSum());
System.out.println("Count From the Data is " + summary.getCount());
//Add a new number to the stream
System.out.println("\n");
summary.accept(10);
System.out.println("Max From the Data is " + summary.getMax());
System.out.println("Min From the Data is " + summary.getMin());
System.out.println("Average From the Data is " + summary.getAverage());
System.out.println("Sum From the Data is " + summary.getSum());
System.out.println("Count From the Data is " + summary.getCount());
}
}
IntSummaryStatistics Example
Max From the Data is 5
Min From the Data is 1
Average From the Data is 3.0
Sum From the Data is 15
Count From the Data is 5
Adding number 10 to the data
Max From the Data is 10
Min From the Data is 1
Average From the Data is 4.166666666666667
Sum From the Data is 25
Count From the Data is 6
Conclusion
How to convert Java Stream to List
How to convert Java Stream to List
// Converting Streams to Collection
Stream<Integer> intStream = Stream.of(1, 2, 3, 4, 5);
List<Integer> list = intStream.collect(Collectors.toList());
System.out.println(list); // prints [1, 2, 3, 4, 5]
Arduino Humadity
#include
#include
dht DHT;
#define DHT11_PIN 7
void setup(){
Serial.begin(9600);
}
void loop(){
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(1000);
}
Ardino Gas Sensors
//#include
#define MQ2pin (0)
//https://robu.in/mq2-sensor-interfacing-with-arduino-gas-and-smoke-detection/
float sensorValue; //variable to store sensor value
void setup()
{
Serial.begin(9600); // sets the serial port to 9600
Serial.println("Gas sensor warming up!");
Serial.println("I can detect 300 - 10000ppm");
delay(20000); // allow the MQ-2 to warm up
}
void loop()
{
sensorValue = analogRead(MQ2pin); // read analog input pin 0
Serial.print("Sensor Value: ");
Serial.print(sensorValue);
Serial.println("");
delay(2000); // wait 2s for next reading
}
Extract content of .war file
jar -xvf blogapp.war

Conclusion
HashMap computeIfPresent() method in Java with Examples
Syntax
V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Example
package corejava.map;
import java.util.HashMap;
import java.util.Map;
public class ComputeIfPresentExample {
public static void main (String argv[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Sunglass", 105);
map.put("Watch", 1501);
newline("Original Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
map.computeIfPresent("Watch", (k,v) -> {return v + v;});
newline("After calling computeIfAbsent Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
}
static void newline(String s) {
System.out.println("\n" + s);
};
}
Original Map Watch -> 1501 Sunglass -> 105 After calling computeIfAbsent Map Watch -> 3002 Sunglass -> 105
Summary
HashMap computeIfAbsent() method in Java with Examples
Syntax
public V computeIfAbsent(K key, Function<? super K, ? extends V> remappingFunction)
Example
package corejava.map;
import java.util.HashMap;
import java.util.Map;
public class ComputeIfAbsentExample {
public static void main (String argv[]) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
newline("Original Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
map.computeIfAbsent(6, k-> { return "six";});
map.computeIfAbsent(7, k -> "seven");
newline("After calling computeIfAbsent Map");
map.forEach((a, b) -> {
System.out.println(a + " -> " + b);
});
}
static void newline(String s) {
System.out.println("\n" + s);
};
}
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five After calling computeIfAbsent Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> six 7 -> seven
Summary
Remove all entries in map by value
Using removeAll
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
map.values().removeAll(Collections.singleton("five"));
newline("After removing values = five");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five 7 -> five After removing values = five 1 -> one 2 -> two 3 -> three 4 -> four
Using removeIf
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
//remove entries where value = five
map.values().removeIf("five"::equals);
newline("After removing values = five");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five 7 -> five After removing values = five 1 -> one 2 -> two 3 -> three 4 -> four
Remove all entries from java map
Method clear()
static void clearALLItemsInMap() {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "five");
newline("Original Map");
map.forEach( (a,b) -> {
System.out.println( a + " -> " + b);
});
//clear the map
map.clear();
newline("After classing clear() Map");
map.forEach( (a,b) -> {
System.out.println(a + " -> " + b);
});
}
Original Map 1 -> one 2 -> two 3 -> three 4 -> four 5 -> five 6 -> five After classing clear() Map empty
Summary
When to User BigInteger in Java
When to use Java BigInteger
java.math.BigInteger
Integer Max and Min value
Print Value of Integer Max and Min
System.out.println(Integer.MAX_VALUE); //2147483647
System.out.println(Integer.MIN_VALUE); //-2147483648
BigInteger a = BigInteger.valueOf(15);
BigInteger b = BigInteger.ONE;
BigInteger result = a.add(b);
System.out.println("Addition of a,b = " + result);
result = a.subtract(b);
System.out.println("Subtration of a,b = " + result);
result = a.divide(b);
System.out.println("Division of a,b = " + result);
result = a.multiply(b);
System.out.println("Multipllication of a,b = " + result);
How to delete .DS_STORE files in current folder and all subfolders
Delete .DS_STORE files in all subfolders
find . -name ".DS_Store" -delete
How to generate Radom Integer in Java between two numbers.
Generate random number
Using Class java.lang.Math
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Using Class java.util.Random
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
Full Example
import java.util.Random;
public class GenerateRandomNumber {
public static void main(String[] args) {
System.out.println(GenerateRandomNumber.generateRandomInteger(35, 40));
System.out.println(GenerateRandomNumber.generateRandomIntegerII(35, 40));
}
private static int generateRandomInteger(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
double r = Math.random();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
private static int generateRandomIntegerII(int rangeStart, int rangeEnd) {
// generate double between 0.0 and 1.0
Random random = new Random();
double r = random.nextDouble();
Integer result = (int) (rangeStart + r * (rangeEnd - rangeStart));
return result;
}
}