Java 16961 (#13236)

* [JAVA-16961] Moved code for article "Create an Empty Map in Java"

* [JAVA-16961] Alter README.md

* [JAVA-16961] Moved code for article "Sorting a Hashset in Java"

* [JAVA-16961] Added links to README.md files

* [JAVA-16961] Revert link changes

* [JAVA-16961] Replaced junit4 with junit5 annotations

* [JAVA-16961] test build

* [JAVA-16961] Added junit annotations

* [JAVA-16961] Added links

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos
2023-01-13 14:37:27 +00:00
committed by GitHub
parent 7f42f403da
commit 2d2d0ed9de
15 changed files with 44 additions and 22 deletions

View File

@@ -2,3 +2,5 @@
- [Using Streams to Collect Into a TreeSet](https://www.baeldung.com/java-stream-collect-into-treeset)
- [A Guide to LinkedHashSet in Java](https://www.baeldung.com/java-linkedhashset)
- [Sorting a HashSet in Java](https://www.baeldung.com/java-sort-hashset)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)

View File

@@ -15,6 +15,12 @@
</parent>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@@ -0,0 +1,55 @@
package com.baeldung.hashset.sorting;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class HashSetUnitTest {
@Test
void givenHashSet_whenUsingCollectionsSort_thenHashSetSorted() {
HashSet<Integer> numberHashSet = new HashSet<>();
numberHashSet.add(2);
numberHashSet.add(1);
numberHashSet.add(4);
numberHashSet.add(3);
// converting HashSet to arraylist
ArrayList<Integer> arrayList = new ArrayList<>(numberHashSet);
// sorting the list
Collections.sort(arrayList);
assertThat(arrayList).containsExactly(1, 2, 3, 4);
}
@Test
void givenHashSet_whenUsingTreeSet_thenHashSetSorted() {
HashSet<Integer> numberHashSet = new HashSet<>();
numberHashSet.add(2);
numberHashSet.add(1);
numberHashSet.add(4);
numberHashSet.add(3);
// TreeSet gets the value of hashSet
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.addAll(numberHashSet);
assertThat(treeSet).containsExactly(1, 2, 3, 4);
}
@Test
void givenHashSet_whenUsingStream_thenHashSetSorted() {
HashSet<Integer> numberHashSet = new HashSet<>();
numberHashSet.add(200);
numberHashSet.add(100);
numberHashSet.add(400);
numberHashSet.add(300);
HashSet<Integer> sortedHashSet = numberHashSet.stream().sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
assertThat(sortedHashSet).containsExactly(100, 200, 300, 400);
}
}