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

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

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

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Practical Generators in Go 1.23 for Database Pagination
  • What Is a Jagged Array in Java With Examples?
  • How To Get Cell Data From an Excel Spreadsheet Using APIs in Java

Trending

  • How to Merge HTML Documents in Java
  • Building an AI/ML Data Lake With Apache Iceberg
  • Monolith: The Good, The Bad and The Ugly
  • AI-Driven Test Automation Techniques for Multimodal Systems
  1. DZone
  2. Data Engineering
  3. Data
  4. Learning Redis Basic Data Structure and Mapping With Java Data Structure

Learning Redis Basic Data Structure and Mapping With Java Data Structure

In this article, we will demonstrate the usage of java data structure with its corresponding Redis data type in terms of java code as a Jedis client.

By 
Tiruvenkatasamy Baskaran user avatar
Tiruvenkatasamy Baskaran
·
Nov. 17, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

We all know that Redis is an in-memory database server which has its own data structure.

String(float and integer)

512MB; Stores string, numerical value, serialized JSON, and binary

list

Stores list of Strings and holds 4 billion entries. It is used to design Queue and Stack. It is implemented as a doubly LinkedList.

set

Allows the unique collection of elements. Supports set operations like difference, intersect, and union.

hash

Collection of field-value pairs and mutable.

The below table is the corresponding java data structure.


String

String stores sequence of characters.

List<String>

Stores list of Strings and holds 4 billion entries. It is used to design Queue and Stack. It is implemented as a doubly LinkedList.

Set<String>

Allows the unique collection of elements. Supports set operations like difference, intersect, and union.

Map<String, String>

Collection of field-value pairs and mutable.

Double

Primitive data type

Long

Primitive data type

Prerequisites

  • Eclipse (any version) with Maven capabilities
  • Java 8+
  • Junit
  • Redis and Jedis

Installing Redis Server on Windows

  1. Click on the link: https://github.com/dmajkic/redis/downloads
  2. Download redis-2.4.5-win32-win64.zip file
  3. Unzip the file and go to 64bit folder. There you can find redis-server.exe
  4. To start the Redis server, execute the redis-server.exe file.

Installing Eclipse-IDE on Windows

  1. Click on the link: https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2020-09/R/eclipse-inst-jre-win64.exe
  2. Download eclipse-inst-jre-win64.exe file and run the eclipse installer.

3.Select Eclipse IDE for Eclipse committers and install

Creating a Maven Project in Eclipse IDE

  1. Open the Eclipse IDE

      2.Go to File  > New > Project

        3.Go to Maven -> Maven Project and click Next.

         4.Select your workspace location and click Next

           

       5.Select quick start maven archetype and click Next.

      6.Enter Group Id, Artifact Id, and package name.


  • Group Id: Fill a groupId for the project of your choice.
  • Artifact Id: Fill artifactId for the project of your choice.
  • Package: java package structure of your choice

     7.The above process will create a project structure like below.

8. Place the HostPort.java file in com.example.demo package.

Java
 




x
20


 
1
package com.example.demo;
2

          
3
public class HostPort {
4
    final private static String defaultHost = "localhost";
5
    final private static Integer defaultPort = 6379;
6
    final private static String defaultPassword = "";
7

          
8
    public static String getRedisHost() {
9
        return defaultHost;
10
    }
11

          
12
    public static Integer getRedisPort() {
13
        return defaultPort;
14
    }
15

          
16
    public static String getRedisPassword() {
17
        return defaultPassword;
18
    }
19
}
20

          


  

9. Add the JedisBasicsTest.java file in com.example.demo package.

Java
 




xxxxxxxxxx
1
143


 
1
package com.example.demo;
2
import static org.hamcrest.MatcherAssert.assertThat;
3
import static org.hamcrest.Matchers.is;
4

          
5
import java.util.Arrays;
6
import java.util.HashMap;
7
import java.util.HashSet;
8
import java.util.List;
9
import java.util.Map;
10
import java.util.Set;
11

          
12
import org.junit.After;
13
import org.junit.Before;
14
import org.junit.Test;
15

          
16
import redis.clients.jedis.Jedis;
17

          
18
public class JedisBasicsTest {
19

          
20
    public static String[] testPlanets = { "Mercury", "Mercury", "Venus", "Earth", "Earth", "Mars", "Jupiter", "Saturn",
21
            "Uranus", "Neptune", "Pluto" };
22

          
23
    private Jedis;
24

          
25
    @Before
26
    public void setUp() {
27
        this.jedis = new Jedis(HostPort.getRedisHost(), HostPort.getRedisPort());
28

          
29
        if (HostPort.getRedisPassword().length() > 0) {
30
            jedis.auth(HostPort.getRedisPassword());
31
        }
32

          
33
        jedis.del("planets");
34
        jedis.del("earth");
35
    }
36

          
37
    @After
38
    public void tearDown() {
39
        jedis.del("planets");
40
        jedis.del("earth");
41
        jedis.close();
42
    }
43

          
44
    @Test
45
    public void testRedisList() {
46
        assertThat(testPlanets.length, is(11));
47

          
48
        /* Add all test planets to the Redis set */
49
        
50
        for (String testPlanet : testPlanets) {
51
            Long result=jedis.rpush("planets", testPlanet);
52
            //System.out.println(result);
53
        }
54

          
55
        // Check the length of the list
56
        Long length = jedis.llen("planets");
57
        System.out.println(length);
58
        assertThat(length, is(11L));
59

          
60
        // Get the planets from the list
61
        // Note: LRANGE is an O(n) command. Be careful running this command
62
        // with high-cardinality sets.
63
        List<String> planets = jedis.lrange("planets", 0, -1);
64
        System.out.println(planets);
65
        assertThat(planets, is(Arrays.asList(testPlanets)));
66

          
67
        // Remove the elements that we know are duplicates
68
        jedis.lrem("planets", 1, "Mercury");
69
        jedis.lrem("planets", 1, "Earth");
70

          
71
        // Drop a planet from the end of the list
72
        String planet = jedis.rpop("planets");
73
        assertThat(planet, is("Pluto"));
74
        length = jedis.llen("planets");
75
        System.out.println(length);
76
        assertThat(length, is(8L));
77
    }
78

          
79
    @Test
80
    public void testRedisSet() {
81
        assertThat(testPlanets.length, is(11));
82

          
83
        // Add all test planets to the Redis set
84
        jedis.sadd("planets", testPlanets);
85

          
86
        // Return the cardinality of the set
87
        Long length = jedis.scard("planets");
88
        System.out.println("length :: "+length);
89
        assertThat(length, is(9L));
90

          
91
        // Fetch all values from the set
92
        // Note: SMEMBERS is an O(n) command. Be careful running this command
93
        // with high-cardinality sets. Consider SSCAN as an alternative.
94
        Set<String> planets = jedis.smembers("planets");
95
        System.out.println("planets :: "+planets);
96

          
97
        // Ensure that a HashSet created and stored in Java memory and the set stored
98
        // in Redis have the same values.
99
        Set<String> planetSet = new HashSet<>(Arrays.asList(testPlanets));
100
        assertThat(planets, is(planetSet));
101

          
102
        // Pluto is, of course, no longer a first-class planet. Remove it.
103
        Long response = jedis.srem("planets", "Pluto");
104
        assertThat(response, is(1L));
105

          
106
        // Now we have 8 planets, as expected.
107
        Long newLength = jedis.scard("planets");
108
        System.out.println("newLength :: "+newLength);
109
        assertThat(newLength, is(8L));
110
    }
111

          
112
    @Test
113
    public void testRedisHash() {
114
        Map<String, String> earthProperties = new HashMap<>();
115
        earthProperties.put("diameterKM", "12756");
116
        earthProperties.put("dayLengthHrs", "24");
117
        earthProperties.put("meanTempC", "15");
118
        earthProperties.put("moonCount", "1");
119

          
120
        // Set the fields of the hash one by one.
121
        for (Map.Entry<String, String> property : earthProperties.entrySet()) {
122
            jedis.hset("earth", property.getKey(), property.getValue());
123
        }
124

          
125
        // Get the hash we just created back from Redis.
126
        Map<String, String> storedProperties = jedis.hgetAll("earth");
127
        System.out.println("storedProperties :: "+storedProperties);
128
        assertThat(storedProperties, is(earthProperties));
129

          
130
        // Setting fields all at once is more efficient.
131
        jedis.hmset("earth", earthProperties);
132
        storedProperties = jedis.hgetAll("earth");
133
        System.out.println("storedProperties :: "+storedProperties);
134
        assertThat(storedProperties, is(earthProperties));
135

          
136
        // Test that we can get a single property.
137
        String diameter = jedis.hget("earth", "diameterKM");
138
        System.out.println("diameter :: "+diameter);
139
        assertThat(diameter, is(earthProperties.get("diameterKM")));
140
    }
141

          
142
}
143

          



10.Replace the pom.xml with the below content.

XML
 
xxxxxxxxxx
1
212


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project
3
        xmlns="http://maven.apache.org/POM/4.0.0"
4
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
6

          
7
    <modelVersion>4.0.0</modelVersion>
8
    <prerequisites>
9
        <maven>3.0.0</maven>
10
    </prerequisites>
11

          
12
    <groupId>RedisDataStructDemo</groupId>
13
    <artifactId>RedisDataStructDemo</artifactId>
14
    <version>1.0</version>
15
    <packaging>jar</packaging>
16

          
17
    <name>RedisDataStructDemo</name>
18

          
19
    <properties>
20
        <redis.host>localhost</redis.host>
21
        <redis.port>6379</redis.port>
22
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24
        <dropwizard.version>1.3.8</dropwizard.version>
25
        <mainClass>com.example.demo.RediSolarApplication</mainClass>
26
    </properties>
27

          
28
    <dependencyManagement>
29
        <dependencies>
30
            <dependency>
31
                <groupId>io.dropwizard</groupId>
32
                <artifactId>dropwizard-bom</artifactId>
33
                <version>${dropwizard.version}</version>
34
                <type>pom</type>
35
                <scope>import</scope>
36
            </dependency>
37
        </dependencies>
38
    </dependencyManagement>
39

          
40
    <dependencies>
41
        <dependency>
42
            <groupId>com.google.inject</groupId>
43
            <artifactId>guice</artifactId>
44
            <version>4.2.2</version>
45
        </dependency>
46
        <dependency>
47
            <groupId>io.dropwizard</groupId>
48
            <artifactId>dropwizard-core</artifactId>
49
        </dependency>
50
        <dependency>
51
            <groupId>io.dropwizard</groupId>
52
            <artifactId>dropwizard-assets</artifactId>
53
        </dependency>
54
        <dependency>
55
            <groupId>io.dropwizard</groupId>
56
            <artifactId>dropwizard-testing</artifactId>
57
        </dependency>
58
        <dependency>
59
            <groupId>redis.clients</groupId>
60
            <artifactId>jedis</artifactId>
61
            <version>3.1.0-m3</version>
62
        </dependency>
63
        <dependency>
64
            <groupId>com.redislabs</groupId>
65
            <artifactId>jredistimeseries</artifactId>
66
            <version>0.9.0</version>
67
        </dependency>
68
        <dependency>
69
            <groupId>javax.xml.bind</groupId>
70
            <artifactId>jaxb-api</artifactId>
71
            <version>2.2.11</version>
72
        </dependency>
73
        <dependency>
74
            <groupId>com.sun.xml.bind</groupId>
75
            <artifactId>jaxb-core</artifactId>
76
            <version>2.2.11</version>
77
        </dependency>
78
        <dependency>
79
            <groupId>com.sun.xml.bind</groupId>
80
            <artifactId>jaxb-impl</artifactId>
81
            <version>2.2.11</version>
82
        </dependency>
83
        <dependency>
84
            <groupId>javax.activation</groupId>
85
            <artifactId>activation</artifactId>
86
            <version>1.1.1</version>
87
        </dependency>
88
        <dependency>
89
            <groupId>junit</groupId>
90
            <artifactId>junit</artifactId>
91
            <version>4.12</version>
92
            <scope>test</scope>
93
        </dependency>
94
        <dependency>
95
            <groupId>org.hamcrest</groupId>
96
            <artifactId>hamcrest-all</artifactId>
97
            <version>1.3</version>
98
            <scope>test</scope>
99
        </dependency>
100
        <dependency>
101
            <groupId>org.mockito</groupId>
102
            <artifactId>mockito-all</artifactId>
103
            <version>1.9.5</version>
104
            <scope>test</scope>
105
        </dependency>
106
    </dependencies>
107

          
108
    <build>
109
        <plugins>
110
            <plugin>
111
                <groupId>org.codehaus.mojo</groupId>
112
                <artifactId>properties-maven-plugin</artifactId>
113
                <version>1.0.0</version>
114
                <executions>
115
                    <execution>
116
                        <phase>initialize</phase>
117
                        <goals>
118
                            <goal>read-project-properties</goal>
119
                        </goals>
120
                        <configuration>
121
                            <files>
122
                                <file>pom.xml</file>
123
                            </files>
124
                        </configuration>
125
                    </execution>
126
                </executions>
127
            </plugin>
128
            <plugin>
129
                <artifactId>maven-shade-plugin</artifactId>
130
                <version>2.4.1</version>
131
                <configuration>
132
                    <createDependencyReducedPom>false</createDependencyReducedPom>
133
                    <transformers>
134
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
135
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
136
                            <mainClass>${mainClass}</mainClass>
137
                        </transformer>
138
                    </transformers>
139
                    <!-- exclude signed Manifests -->
140
                    <filters>
141
                        <filter>
142
                            <artifact>*:*</artifact>
143
                            <excludes>
144
                                <exclude>META-INF/*.SF</exclude>
145
                                <exclude>META-INF/*.DSA</exclude>
146
                                <exclude>META-INF/*.RSA</exclude>
147
                            </excludes>
148
                        </filter>
149
                    </filters>
150
                </configuration>
151
                <executions>
152
                    <execution>
153
                        <phase>package</phase>
154
                        <goals>
155
                            <goal>shade</goal>
156
                        </goals>
157
                    </execution>
158
                </executions>
159
            </plugin>
160
            <plugin>
161
                <artifactId>maven-jar-plugin</artifactId>
162
                <version>3.0.2</version>
163
                <configuration>
164
                    <archive>
165
                        <manifest>
166
                            <addClasspath>true</addClasspath>
167
                            <mainClass>${mainClass}</mainClass>
168
                        </manifest>
169
                    </archive>
170
                </configuration>
171
            </plugin>
172
            <plugin>
173
                <artifactId>maven-compiler-plugin</artifactId>
174
                <version>3.6.1</version>
175
                <configuration>
176
                    <source>1.8</source>
177
                    <target>1.8</target>
178
                </configuration>
179
            </plugin>
180
            <plugin>
181
                <artifactId>maven-source-plugin</artifactId>
182
                <version>3.0.1</version>
183
                <executions>
184
                    <execution>
185
                        <id>attach-sources</id>
186
                        <goals>
187
                            <goal>jar</goal>
188
                        </goals>
189
                    </execution>
190
                </executions>
191
            </plugin>
192
        </plugins>
193
    </build>
194

          
195
    <reporting>
196
        <plugins>
197
            <plugin>
198
                <artifactId>maven-project-info-reports-plugin</artifactId>
199
                <version>2.8.1</version>
200
                <configuration>
201
                    <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
202
                    <dependencyDetailsEnabled>false</dependencyDetailsEnabled>
203
                </configuration>
204
            </plugin>
205
            <plugin>
206
                <artifactId>maven-javadoc-plugin</artifactId>
207
                <version>2.10.3</version>
208
            </plugin>
209
        </plugins>
210
    </reporting>
211
</project>
212

          


Running the Code

1.Build the Maven project and run the test case as shown below

2.Check the test result.


Now, we learned Redis' basic data structure and working with the Jedis java API.

Further, this use case can be adapted according to your requirements.

Feel free to ask any questions.

Data structure Data (computing) Java (programming language) Redis (company) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Practical Generators in Go 1.23 for Database Pagination
  • What Is a Jagged Array in Java With Examples?
  • How To Get Cell Data From an Excel Spreadsheet Using APIs in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

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!