Getting Started with Java Collection

[Here](https://yk0807.com/techblog/2020/03/05/java%e3%81%ae%e3%82%b3%e3%83%ac%e3%82%af%e3%82% b7% e3% 83% a7% e3% 83% b3% e5% 85% a5% e9% 96% 80% ef% bc% 8b% ce% b1 /) blog post posted on Qiita.

0. Preface

Not limited to Java, there are many cases where arrays alone do not work well for organizing data in programming. Therefore, the data structure becomes important, and the expression method around it varies depending on the language.

For C ++, there are containers for vector, list, and standard library, and for C #, it seems to use LINQ. With PHP, you can do a lot with arrays (you need to be careful when using them). With Python, it feels like using list types, tuples, dictionaries, etc. according to the purpose.

1. What is a collection framework?

Well, Java. Java uses a collection framework. In the collection framework, lists (values are ordered), sets (values are not necessarily ordered, but only one has the same value), maps (values correspond to each key). The data structure necessary to express data such as (the one that was done) is complete (there is also a Deque that can only input and output values from both ends, but it is omitted this time because its use is limited).

2. List

First of all, a list. The list is ** containing data for each index starting from ** 0. It is implemented based on the List interface, and two classes, ArrayList (variable length array) and LinkedList (linked list), are often used. ArrayList is like vector in C ++. Java also has a Vector class, but this is deprecated in Java 8 and later. Each is defined as follows.

List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();

Which class you define in is determined when you call the constructor. By the way, the <> between the class and the parenthesis is called the diamond operator, which is a notation for omitting the element type. Frequently used operations are as follows. Although it is described for ArrayList, the processing to be performed is the same even for LinkedList.

List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
arrayList.add("Apple");  //Element at the end of the list"Apple"Add
arrayList.get(5);  //5 in the list+Get the first element
arrayList.set(3, "Orange");  //List 3+The value of the first element"Orange"Set to
arrayList.remove(4); //4 in the list+Remove the first element and decrement subsequent indexes by one
arrayList.size();  //Returns the number of elements in the list
arrayList.clear();  //Empty the list
//Output the element list of arrayList
for (String data : arrayList) {
	System.out.println(data);
}

However, I wrote above that "the processing to be performed is the same", but since the implementation method is different between ArrayList and LinkedList, there are strengths and weaknesses in each. For get and set, ArrayList where each element is indexed in memory is faster, and for add and remove, link information between elements (image like pointer in C language. Java does not have pointer) LinkedList connected by) is faster. So, if you bring some large data from a database and the main purpose is to access the elements in it, ArrayList is suitable, and if data is frequently added or deleted from the list, LinkedList is suitable.

3. Set

A set is a collection of data like a list, but unlike a list, there is no ** index, and you can't have more than one with the same value **. I hope that those who have studied mathematics at university can imagine sets and topological sets. This is implemented based on the Set interface, and HashSet, TreeSet, and LinkedHashSet are often used. Each is defined as follows.

Set<String> hashSet = new HashSet<>();
Set<String> treeList = new TreeList<>();
Set<String> linkedHashSet = new LinkedHashSet<>();

The basic operation is as follows. I wrote for HashSet, but the other two are the same. Please be careful where ** get and set are missing **.

Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>();
Set<String> linkedHashSet = new LinkedHashSet<>();
hashSet.add("Banana");  //To the elements of the set"Banana"If not included, add
hashSet.remove("Lemon"); //To the set"Lemon"If it is included, delete it
hashSet.size();  //Returns the number of elements in the set
//Output a list of hashSet elements
for (String data : hashSet) {
	System.out.println(data);
}

The difference between HashSet, TreeSet, and LinkedHashSet is that HashSet is faster, but the order is not guaranteed at all, TreeSet keeps the elements sorted, and LinkedHashSet keeps the order in which the elements were added.

treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Apple");
for (String data : treeSet) {
	System.out.println(data);
}

Then, it is output in the order of "Apple"-> "Banana"-> "Orange".

linkedHashSet.add("Banana"); 
linkedHashSet.add("Orange");
linkedHashSet.add("Apple"); 
for (String data : linkedHashSet) {
	System.out.println(data);
}

Then, it will be output in the order of "Banana"-> "Orange"-> "Apple".

4. Map

Maps hold not only values, but also ** data in combination with keys that specify values **. Keys are unique on the map (there are no multiple identical values), but multiple values can be the same. Maps are implemented based on the Map interface, and HashMap, TreMap, and LinkedHashMap are often used. Each is defined as follows.

Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();

The basic operation is as follows. Use the put method to add a key / value combination to the map.

Map<String, Integer> hashMap = new HashMap<>();
Map<String, Integer> treeMap = new TreeMap<>();
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
hashMap.put("Tomato", 300);  //Map key"Tomato"Set the value of to 300
hashMap.get("Tomato");  //The map key is"Tomato"Returns the value of (null if not)
hashMap.remove("Lemon"); //The key is on the map"Lemon"Delete if it contains
hashMap.size();  //Returns the number of elements in the map
//Key for each element of the map:Output in the form of value
for (Map.Entry<String, Integer> data : hashSet.entrySet()) {
	System.out.println(data.getKey() + ":" + data.getValue());
}

It takes a little more time to output all the data than others. Like the set, HashMap is fast but the order is not guaranteed, TreeMap holds the data in the order of the keys, and LinkedHashMap holds the data in the order in which the data was added.

5. At the end

I took a quick look at the collections that I usually use in Java. There seem to be several others, but if you can master the ones introduced this time according to the purpose, I think that there will not be much trouble in handling data in Java. I used to define data for a combination of a name and an object in HashMap, but I realized that it was necessary to output in ascending order of the name, so I hurriedly rewrote it in TreeMap. When you use a collection, think about what you are aiming for and choose the one that works best for you.

Recommended Posts

Getting Started with Java Collection
Getting Started with Java Basics
Getting started with Java lambda expressions
Getting Started with Ruby for Java Engineers
Getting Started with DBUnit
Getting Started with Ruby
Getting Started with Java Starting from 0 Part 1
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
Links & memos for getting started with Java (for myself)
Getting Started with Java 1 Putting together similar things
Getting started with Kotlin to send to Java developers
Getting Started with Doma-Annotation Processing
Getting Started with JSP & Servlet
Getting Started with Spring Boot
Getting Started with Ruby Modules
Getting started with Java programs using Visual Studio Code
☾ Java / Collection
Java9 collection
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Getting Started with Java_Chapter 5_Practice Exercises 5_4
[Google Cloud] Getting Started with Docker
Getting Started with Docker with VS Code
Getting started with Java and creating an AsciiDoc editor with JavaFX
Getting Started with Doma-Criteria API Cheat Sheet
Returning to the beginning, getting started with Java ② Control statements, loop statements
Getting Started with Docker for Mac (Installation)
Getting Started with Parameterization Testing in JUnit
Java Reintroduction-Java Collection
Getting Started with Ratpack (4)-Routing & Static Content
Getting started with the JVM's GC mechanism
Getting Started with Language Server Protocol with LSP4J
[Java] Collection framework
Getting Started with Creating Resource Bundles with ListResoueceBundle
Getting Started with Machine Learning with Spark "Price Estimate" # 1 Loading Datasets with Apache Spark (Java)
Getting Started with Java_Chapter 8_About Instances and Classes
Getting Started with Doma-Using Projection with the Criteira API
[Java] Create a collection with only one element
Getting Started with Doma-Using Subqueries with the Criteria API
Getting Started with Doma-Using Joins with the Criteira API
Getting Started with Doma-Introduction to the Criteria API
I tried Getting Started with Gradle on Heroku
Install java with Homebrew
Expired collection of java
Java collection interview questions
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
Switch java with direnv
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Get started with Gradle
Endian conversion with JAVA
Experienced Java users get started with Android application development
Get started with serverless Java with the lightweight framework Micronaut!
Going back to the beginning and getting started with Java ① Data types and access modifiers
Proceed with Rust official documentation on Docker container (1. Getting started)
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java