I have a List
of Pin
objects (List<Pin>
) where the Pin
class has the following attributes:
String pinNumber, String pinType, Date insertDate
I would like to get a HashMap
with <String pinNumber, int count>
that have the distinct pinNumber telling me how many distinct pinNumber are in the List<Pin>
and a count of each.
So the way I know of to do this is to:
List<Pin>
HashMap
contains already the key value of the pinNumber and:I would like to do the same for each of the fields from the Pin
object.
I am sure there should be an easier way to do this?
Maybe Guava has something simpler?
Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. Display all records from the table using select statement.
Note that there are four records with a last_name value of “smith”. The four records have three distinct values for the first_name field (“mike, “william”, and “mark”). To count the unique values, use "distinct()" rather than "find()", and "length" rather than "count()".
Count is the total number of values. Count Distinct in the number of unique values. Count Distinct will always be equal to or less than Count. Helpful (1) Count is the total number of values.
If you have the possibility to use Java 8 (and since what you want to do basically sounds like a "group by" operation), this can be solved in an elegant way using the new Stream API (as hinted by user vallismortis):
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Pin> pins = Arrays.asList(
new Pin("PIN-1", "T1", new Date()),
new Pin("PIN-1", "T2", new Date()),
new Pin("PIN-1", "T3", new Date()),
new Pin("PIN-2", "T2", new Date()),
new Pin("PIN-2", "T2", new Date()),
new Pin("PIN-3", "T2", new Date())
);
Map<String, Long> map = pins.stream().collect(groupingBy(Pin::getPinNumber, counting()));
System.out.println("map = " + map);
}
}
class Pin {
String pinNumber;
String pinType;
Date insertDate;
public Pin(String pinNumber, String pinType, Date insertDate) {
this.pinNumber = pinNumber;
this.pinType = pinType;
this.insertDate = insertDate;
}
public String getPinNumber() {
return pinNumber;
}
public String getPinType() {
return pinType;
}
public Date getInsertDate() {
return insertDate;
}
}
Output:
map = {PIN-1=3, PIN-3=1, PIN-2=2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With