DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

  1. DZone
  2. Data Engineering
  3. Data
  4. Java HashMap Search and Sort

Java HashMap Search and Sort

A HashMap has plenty of uses, so let's see how you can find keys and values, load data from a CSV file into one, and use it for sorting.

By 
Jay Sridhar user avatar
Jay Sridhar
·
Mar. 16, 17 · Tutorial
Likes (26)
Comment (1)

Save
Tweet
Share
82.97K Views

Join the DZone community and get the full member experience.

Join For Free

“What you stay focused on will grow.”
― Roy T. Bennett

Introduction

Having explored HashMap in several previous articles (here and here), let us now learn how to search and sort a HashMap by key as well as value.

Image title

Finding Keys and Values in HashMap

Finding a key in a HashMap is quite simple. The HashMap API provides the containsKey() method, which tells you whether the key exists.

​x
1
Map<String,Integer> namefreq = new HashMap<>();
2
namefreq.put("Petra", 14);
3
namefreq.put("Mario", 11);
4
namefreq.put("Kasandra", 23);
5
namefreq.put("Charity", 18);
6
namefreq.put("Minerva", 5);
7
if ( namefreq.containsKey("Charity") ) {
8
​
9
}


Finding a value is also easy given the method containsValue().

3
1
if ( namefreq.containsValue(10) ) {
2
​
3
}


Pretty simple, right? Well, what if you need to find not a particular value but search for a general expression, such as names starting with say “A”. Gets a bit more involved.

Loading CSV Into HashMap

The following search and sort examples make use of a name frequency table, which is loaded from CSV using the following code. It streams lines from a CSV file, splits the line into fields, selects values for the “CA” state, and stores the value as a Map of (year => count). (The data is from US Census Bureau which publishes name frequency counts for each year.)

The code creates a multi-HashMap with the structure:

3
1
(name => ((year => count),
2
          (year => count)),
3
...


18
1
Pattern pattern = Pattern.compile(",");
2
String csvFile = "StateNames.csv";
3
try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){
4
    Map<String,Map<Integer,Integer>> namefreq = in
5
    .lines()
6
    .skip(1)
7
    .map(x -> pattern.split(x))
8
    .filter(x -> x[4].equals("CA"))
9
    .collect(HashMap::new, (map, x) ->
10
         map.compute(x[1], (k, v) -> {
11
             if ( v == null )
12
                 v = new HashMap<Integer,Integer>();
13
             v.put(Integer.parseInt(x[2]),
14
                   Integer.parseInt(x[5]));
15
             return v;
16
             }),
17
         Map::putAll);
18
}


Here is a snippet of the sample data being loaded.

11
1
Id,Name,Year,Gender,State,Count
2
1,Mary,1910,F,AK,14
3
2,Annie,1910,F,AK,12
4
3,Anna,1910,F,AK,10
5
4,Margaret,1910,F,AK,8
6
5,Helen,1910,F,AK,7
7
6,Elsie,1910,F,AK,6
8
7,Lucy,1910,F,AK,6
9
8,Dorothy,1910,F,AK,5
10
9,Mary,1911,F,AK,12
11
10,Margaret,1911,F,AK,7


Search Key in HashMap

The following code searches for a key ending with “x” and prints the matches.

18
1
namefreq
2
    .entrySet()
3
    .stream()
4
    .filter(e -> e.getKey().endsWith("x"))
5
    .forEach(e -> {
6
        System.out.println(e.getKey() + " :");
7
        e.getValue().forEach((kk, vv) -> {
8
            System.out.println(" " + kk + " => " + vv);
9
        });
10
    });
11
​
12
​
13
Rex :
14
 1959 => 86
15
Margaux :
16
 2003 => 8
17
Maxx :
18
 2010 => 28


Search Value in HashMap

Let us now search for a value in the HashMap using the same method. Before we do that, let us total the names for each year and store it under the key 0 for each name. Something like this:

5
1
Elza :
2
  0 => 10
3
  1993 => 5
4
  2014 => 5
5
...


We compute the total value with the following code. It computes a total of the existing mappings of (year => count) and stores it under key 0.

12
1
namefreq
2
    .entrySet()
3
    .stream()
4
    .forEach(e -> {
5
        Map<Integer,Integer> v = e.getValue();
6
        int tot = v
7
        .entrySet()
8
        .stream()
9
        .reduce(0, (x, ee) -> x + ee.getValue(),
10
            (x, y) -> x+y);
11
        v.put(0, tot);
12
    });


Let us now search the HashMap for names occurring more than 1000 times.

18
1
namefreq
2
    .entrySet()
3
    .stream()
4
    .filter(e -> e.getValue().getOrDefault(0, 0) > 1000)
5
    .forEach(e ->
6
         System.out.println(e.getKey()+" : "+e.getValue().get(0)));
7
​
8
​
9
...
10
Solomon : 1967
11
Javier : 28472
12
Esther : 16974
13
Lenora : 1261
14
Sam : 6971
15
Lenore : 1261
16
Rowan : 1297
17
Lukas : 2888
18
...


The actual search is being performed by the following segment:

1
1
.filter(e -> e.getValue().getOrDefault(0, 0) > 1000)


Here, you can use an expression of arbitrary complexity to search for exactly what you need. In the following example, we search for key containing the string “mon” and total value more than 1000. The results are stored in another HashMap (for further processing).

15
1
Map<String,Map<Integer,Integer>> subset = namefreq
2
    .entrySet()
3
    .stream()
4
    .filter(e ->  e.getKey().contains("mon")&&e.getValue().getOrDefault(0, 0) > 1000)
5
    .collect(HashMap::new,
6
         (m, e) -> m.put(e.getKey(), e.getValue()),
7
         Map::putAll);
8
subset.forEach((k, v) -> System.out.println(k + " : " + v.get(0)));
9
​
10
​
11
Simone : 3114
12
Desmond : 2498
13
Ramona : 8139
14
Raymond : 60506
15
...


Sort HashMap by Key

To sort a HashMap by key and print the mappings, we can do something like this.

21
1
namefreq
2
    .entrySet()
3
    .stream()
4
    .sorted((x, y) -> x.getKey().compareTo(y.getKey()))
5
    .forEach(e -> {
6
        System.out.println(e.getKey() + " :");
7
        e.getValue().forEach((kk, vv) -> {
8
            System.out.println(" " + kk + " => " + vv);
9
        });
10
    });
11
​
12
​
13
Lylia :
14
 0 => 6
15
 2009 => 6
16
Lyliana :
17
 0 => 15
18
 2007 => 5
19
 1998 => 5
20
 1999 => 5
21
...


To store the result (sorted map), we use a LinkedHashMap (which preserves the insertion order) as follows.

18
1
Map<String,Map<Integer,Integer>> subset = namefreq
2
    .entrySet()
3
    .stream()
4
    .sorted((x, y) -> x.getKey().compareTo(y.getKey()))
5
    .collect(LinkedHashMap::new,
6
         (m, e) -> m.put(e.getKey(), e.getValue()),
7
         Map::putAll);
8
subset.forEach((k, v) -> System.out.println(k + " : " + v.get(0)));
9
​
10
​
11
Byanca : 90
12
Byanka : 79
13
Byran : 65
14
Byron : 7254
15
Cache : 10
16
Cadance : 30
17
Cade : 1874
18
...


Sort HashMap by Value

Sorting the HashMap by value is very similar to the above example. The following code sorts the name-count HashMap by total-count and prints the top 20 names.

21
1
namefreq
2
    .entrySet()
3
    .stream()
4
    .sorted((x, y) ->
5
        y.getValue().get(0).compareTo(x.getValue().get(0)))
6
    .limit(20)
7
    .forEach(x -> System.out.println(x.getKey() + " => " +
8
                     x.getValue().get(0)));
9
​
10
​
11
Michael => 422157
12
David => 364853
13
Robert => 347637
14
John => 310120
15
James => 274168
16
Daniel => 244229
17
Richard => 222633
18
Christopher => 215728
19
William => 209173
20
Anthony => 174064
21
...


Summary

Searching for a key in a HashMap involves applying a filtering pipeline to the entries. The same method is also applicable to search for the HashMap values. In fact, arbitrarily complex expressions can be used with such a pipeline for search. We also learned how to sort the HashMap by keys or values and possibly store the results in a LinkedHashMap.

See Also

  • Java Collections Introduction gives an overall picture of the most important classes and interfaces.
  • Java Collections – HashMap presents parsing a CSV to a HashMap as well as a multi-map.
Data structure Sort (Unix) Java (programming language)

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

    March 22, 2017 Weekly Digest

  • Java Inside Docker: What You Must Know to Not FAIL

  • Java HashMap Search and Sort

  • Microservices With Apache Camel

  • An Introduction To Functional Programming in Java 8 (Part 4): Splitter

  • Building Secure Systems Checklist

  • Sudo (Board Game) [Comic]

  • So, You've Inherited a Legacy Codebase

  • This Week in Hadoop and More: Spark, Keras, and Deep Learning

  • 21 Automated Deployment Tools You Should Know

  • SQL or NoSQL, That Is The Question!

  • RESTful SNMP Over HTTP: Part I

  • Adding React-Bootstrap to a React App

  • Spring Time With Arduino

  • Managing State in Angular with ngrx/store

  • A Short Introduction to Serverless Architecture

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!