I am trying to count how many times a key value appears in a map. What i would like to do is count and return the number of times a duplicate name appears and the gender in the JSON array and return it. So with the data below it should return:
Female: 2 Male: 2
with 2 being the amount of times a duplicate name appears.
So far i have read my JSON data from a file into java objects through the use of ObjectMappers and parsers. But not sure how to go about counting the duplicate names and putting it into a variable of a Gender. I have tried using a statement to match a string (map.get(i).get("fullName") == Williams) but it didnt work. Anyone got any ideas or know of a better way to do this. Thanks
My code:
ObjectMapper mapper = new ObjectMapper();
JSONParser parser = new JSONParser();
JSONObject jsonobj = (JSONObject) parser.parse(new FileReader("data.json"));
JSONArray jsons = (JSONArray) jsonobj.get("Person");
//Map<Integer, Map<String, String>> jsonmaps = new HashMap<Integer, Map<String, String>>();
int i = 0;
List<Map<String, String>> map = new ArrayList();
for (Object j : jsons) {
map.add(mapper.readValue(j.toString(), new TypeReference<Map<String, String>>() {}));
i++;
}
// for testing purposes
//System.out.println(map.get(1).get("fullName"));
//System.out.println(map.get(1).get("age"));
//System.out.println(map.get(1).get("Gender"));
//System.out.println(map.get(1).get("adult"));
//System.out.println(map.get(1).get("dob"));
}
JSON file:
{
"fullName": "Bob Wilkins",
"age": 25,
"gender": "male"
},
{
"fullName": "Hannah Williams",
"age": 49,
"gender": "Female",
"isAdult": true,
"dob": 29/12/1968
},
{
"fullName": "Charlie Smith",
"age": 10,
"gender": "Male",
"isAdult": false,
"dob": 21/05/2008
},
{
"fullName": "Hannah Williams",
"age": 31,
"gender": "Female",
"isAdult": true,
"dob": 13/02/1987
},
{
"fullName": "Charlie Smith",
"age": 25,
"gender": "Male",
"isAdult": true,
"dob": 08/08/1994
},
.....
The following does a grouping on gender
, then groups each collection by fullName
. The result is a Map<String, Long>
, where values have been limited to those greater than 1, then added.
Map<String, Long> counts =
map.stream()
.collect(Collectors.groupingBy(m -> m.get("gender")))
.entrySet()
.stream()
.map(entry -> new SimpleEntry<>(entry.getKey(),
entry.getValue().stream()
.collect(Collectors.groupingBy(m -> m.get("fullName"),
Collectors.counting()))
.values().stream()
.mapToLong(l -> l)
.filter(value -> value > 1).sum()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
When maps
is the test data in the question, the result is:
{Male=2, Female=2, male=0}
So this can be run on your map
list.
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.