Merge branch 'master' into BAEL-6421-PrintWriter-write-vs-print
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.inetspi;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.baeldung.inetspi.providers.CustomAddressResolverImpl;
|
||||
|
||||
public class InetAddressSPI {
|
||||
public String usingGetByName(String host) throws UnknownHostException {
|
||||
InetAddress inetAddress = InetAddress.getByName(host);
|
||||
return inetAddress.getHostAddress();
|
||||
}
|
||||
|
||||
public String[] usingGetAllByName(String host) throws UnknownHostException {
|
||||
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
|
||||
return Arrays.stream(inetAddresses).map(InetAddress::getHostAddress).toArray(String[]::new);
|
||||
}
|
||||
|
||||
public String usingGetByIp(byte[] ip) throws UnknownHostException {
|
||||
InetAddress inetAddress = InetAddress.getByAddress(ip);
|
||||
|
||||
return inetAddress.getHostName();
|
||||
}
|
||||
|
||||
public String usingGetByIpAndReturnsCannonName(byte[] ip) throws UnknownHostException {
|
||||
InetAddress inetAddress = InetAddress.getByAddress(ip);
|
||||
|
||||
return inetAddress.getCanonicalHostName();
|
||||
}
|
||||
|
||||
public String getHostUsingCustomImpl(byte[] ip) throws UnknownHostException {
|
||||
|
||||
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
|
||||
return imp.get(null).lookupByAddress(ip);
|
||||
}
|
||||
|
||||
public Stream<InetAddress> getIpUsingCustomImpl(String host) throws UnknownHostException {
|
||||
|
||||
CustomAddressResolverImpl imp = new CustomAddressResolverImpl();
|
||||
return imp.get(null).lookupByName(host, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.inetspi;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Registry {
|
||||
private final Map<String, List<byte[]>> registry;
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(Registry.class.getName());
|
||||
|
||||
public Registry() {
|
||||
registry = loadMapWithData();
|
||||
}
|
||||
|
||||
public Stream<InetAddress> getAddressesfromHost(String host) throws UnknownHostException {
|
||||
LOGGER.info("Performing Forward Lookup for HOST : " + host);
|
||||
if (!registry.containsKey(host)) {
|
||||
throw new UnknownHostException("Missing Host information in Resolver");
|
||||
}
|
||||
return registry.get(host)
|
||||
.stream()
|
||||
.map(add -> constructInetAddress(host, add))
|
||||
.filter(Objects::nonNull);
|
||||
}
|
||||
|
||||
public String getHostFromAddress(byte[] arr) throws UnknownHostException {
|
||||
LOGGER.info("Performing Reverse Lookup for Address : " + Arrays.toString(arr));
|
||||
for (Map.Entry<String, List<byte[]>> entry : registry.entrySet()) {
|
||||
if (entry.getValue()
|
||||
.stream()
|
||||
.anyMatch(ba -> Arrays.equals(ba, arr))) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
throw new UnknownHostException("Address Not Found");
|
||||
}
|
||||
|
||||
private Map<String, List<byte[]>> loadMapWithData() {
|
||||
return Map.of("baeldung-local.org", List.of(new byte[] { 1, 2, 3, 4 }));
|
||||
}
|
||||
|
||||
private static InetAddress constructInetAddress(String host, byte[] address) {
|
||||
try {
|
||||
return InetAddress.getByAddress(host, address);
|
||||
} catch (UnknownHostException unknownHostException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.inetspi.providers;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.spi.InetAddressResolver;
|
||||
import java.net.spi.InetAddressResolverProvider;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.baeldung.inetspi.Registry;
|
||||
|
||||
public class CustomAddressResolverImpl extends InetAddressResolverProvider {
|
||||
|
||||
private static Logger LOGGER = Logger.getLogger(CustomAddressResolverImpl.class.getName());
|
||||
|
||||
private static Registry registry = new Registry();
|
||||
|
||||
@Override
|
||||
public InetAddressResolver get(Configuration configuration) {
|
||||
LOGGER.info("Using Custom Address Resolver :: " + this.name());
|
||||
LOGGER.info("Registry initialised");
|
||||
return new InetAddressResolver() {
|
||||
@Override
|
||||
public Stream<InetAddress> lookupByName(String host, LookupPolicy lookupPolicy) throws UnknownHostException {
|
||||
return registry.getAddressesfromHost(host);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String lookupByAddress(byte[] addr) throws UnknownHostException {
|
||||
return registry.getHostFromAddress(addr);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "CustomInternetAddressResolverImpl";
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.inetspi;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InetAddressSPIUnitTest {
|
||||
@Test
|
||||
public void givenInetAddress_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
|
||||
InetAddressSPI spi = new InetAddressSPI();
|
||||
Assert.assertNotNull(spi.usingGetByName("www.google.com"));
|
||||
Assert.assertTrue(spi.usingGetAllByName("www.google.com").length > 1);
|
||||
Assert.assertNotNull(spi.usingGetByIp(InetAddress.getByName("www.google.com")
|
||||
.getAddress()));
|
||||
Assert.assertNotNull(spi.usingGetByIpAndReturnsCannonName(InetAddress.getByName("www.google.com")
|
||||
.getAddress()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomInetAddressImplementation_whenUsingInetAddress_thenPerformResolution() throws UnknownHostException {
|
||||
InetAddressSPI spi = new InetAddressSPI();
|
||||
Assert.assertEquals("baeldung-local.org", spi.getHostUsingCustomImpl(new byte[] { 1, 2, 3, 4 }));
|
||||
Stream<InetAddress> response = spi.getIpUsingCustomImpl("baeldung-local.org");
|
||||
Assert.assertArrayEquals(new byte[] { 1, 2, 3, 4 }, response.findFirst()
|
||||
.get()
|
||||
.getAddress());
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
public class PatternCaseLabels {
|
||||
|
||||
static String processInputOld(String input) {
|
||||
String output;
|
||||
switch (input) {
|
||||
case null -> output = "Oops, null";
|
||||
case String s -> {
|
||||
if ("Yes".equalsIgnoreCase(s)) {
|
||||
output = "It's Yes";
|
||||
} else if ("No".equalsIgnoreCase(s)) {
|
||||
output = "It's No";
|
||||
} else {
|
||||
output = "Try Again";
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
static String processInputNew(String input) {
|
||||
String output;
|
||||
switch (input) {
|
||||
case null -> output = "Oops, null";
|
||||
case String s when "Yes".equalsIgnoreCase(s) -> output = "It's Yes";
|
||||
case String s when "No".equalsIgnoreCase(s) -> output = "It's No";
|
||||
case String s -> output = "Try Again";
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
public class RecordPattern {
|
||||
|
||||
record Point(int x, int y) {}
|
||||
|
||||
public static int beforeRecordPattern(Object obj) {
|
||||
int sum = 0;
|
||||
if(obj instanceof Point p) {
|
||||
int x = p.x();
|
||||
int y = p.y();
|
||||
sum = x+y;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static int afterRecordPattern(Object obj) {
|
||||
if(obj instanceof Point(int x, int y)) {
|
||||
return x+y;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
enum Color {RED, GREEN, BLUE}
|
||||
|
||||
record ColoredPoint(Point point, Color color) {}
|
||||
|
||||
record RandomPoint(ColoredPoint cp) {}
|
||||
|
||||
public static Color getRamdomPointColor(RandomPoint r) {
|
||||
if(r instanceof RandomPoint(ColoredPoint cp)) {
|
||||
return cp.color();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
public class StringTemplates {
|
||||
|
||||
public String getStringTemplate() {
|
||||
String name = "Baeldung";
|
||||
return STR."Welcome to \{name}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
public class SwitchPattern {
|
||||
|
||||
static class Account{
|
||||
double getBalance() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static class SavingsAccount extends Account {
|
||||
@Override
|
||||
double getBalance() {
|
||||
return 100;
|
||||
}
|
||||
}
|
||||
|
||||
static class TermAccount extends Account {
|
||||
@Override
|
||||
double getBalance() {
|
||||
return 1000;
|
||||
}
|
||||
}
|
||||
static class CurrentAccount extends Account {
|
||||
@Override
|
||||
double getBalance() {
|
||||
return 10000;
|
||||
}
|
||||
}
|
||||
|
||||
static double getBalanceWithOutSwitchPattern(Account account) {
|
||||
double balance = 0;
|
||||
if(account instanceof SavingsAccount sa) {
|
||||
balance = sa.getBalance();
|
||||
}
|
||||
else if(account instanceof TermAccount ta) {
|
||||
balance = ta.getBalance();
|
||||
}
|
||||
else if(account instanceof CurrentAccount ca) {
|
||||
balance = ca.getBalance();
|
||||
}
|
||||
return balance;
|
||||
}
|
||||
|
||||
static double getBalanceWithSwitchPattern(Account account) {
|
||||
double result;
|
||||
switch (account) {
|
||||
case null -> throw new IllegalArgumentException("Oops, account is null");
|
||||
case SavingsAccount sa -> result = sa.getBalance();
|
||||
case TermAccount ta -> result = ta.getBalance();
|
||||
case CurrentAccount ca -> result = ca.getBalance();
|
||||
default -> result = account.getBalance();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PatternCaseLabelsUnitTest {
|
||||
|
||||
@Test
|
||||
void whenProcessInputOldWayWithYes_thenReturnOutput() {
|
||||
assertEquals("It's Yes", PatternCaseLabels.processInputOld("Yes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputOldWayWithNo_thenReturnOutput() {
|
||||
assertEquals("It's No", PatternCaseLabels.processInputOld("No"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputOldWayWithNull_thenReturnOutput() {
|
||||
assertEquals("Oops, null", PatternCaseLabels.processInputOld(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputOldWayWithInvalidOption_thenReturnOutput() {
|
||||
assertEquals("Try Again", PatternCaseLabels.processInputOld("Invalid Option"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputNewWayWithYes_thenReturnOutput() {
|
||||
assertEquals("It's Yes", PatternCaseLabels.processInputNew("Yes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputNewWayWithNo_thenReturnOutput() {
|
||||
assertEquals("It's No", PatternCaseLabels.processInputNew("No"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputNewWayWithNull_thenReturnOutput() {
|
||||
assertEquals("Oops, null", PatternCaseLabels.processInputNew(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenProcessInputNewWayWithInvalidOption_thenReturnOutput() {
|
||||
assertEquals("Try Again", PatternCaseLabels.processInputNew("Invalid Option"));
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.java21.RecordPattern.Color;
|
||||
import com.baeldung.java21.RecordPattern.ColoredPoint;
|
||||
import com.baeldung.java21.RecordPattern.Point;
|
||||
import com.baeldung.java21.RecordPattern.RandomPoint;
|
||||
|
||||
class RecordPatternUnitTest {
|
||||
|
||||
@Test
|
||||
void whenNoRecordPattern_thenReturnOutput() {
|
||||
assertEquals(5, RecordPattern.beforeRecordPattern(new Point(2, 3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRecordPattern_thenReturnOutput() {
|
||||
assertEquals(5, RecordPattern.afterRecordPattern(new Point(2, 3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenRecordPattern_thenReturnColorOutput() {
|
||||
ColoredPoint coloredPoint = new ColoredPoint(new Point(2, 3), Color.GREEN);
|
||||
RandomPoint randomPoint = new RandomPoint(coloredPoint);
|
||||
assertEquals(Color.GREEN, RecordPattern.getRamdomPointColor(randomPoint));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StringTemplateUnitTest {
|
||||
|
||||
@Test
|
||||
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||
StringTemplates stringTemplates = new StringTemplates();
|
||||
assertEquals("Welcome to Baeldung", stringTemplates.getStringTemplate());
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.java21;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SwitchPatternUnitTest {
|
||||
|
||||
@Test
|
||||
void whenNoSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
|
||||
assertEquals(100, SwitchPattern.getBalanceWithOutSwitchPattern(savingsAccount), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenSwitchPattern_thenReturnSavingsAccountBalance() {
|
||||
SwitchPattern.SavingsAccount savingsAccount = new SwitchPattern.SavingsAccount();
|
||||
assertEquals(100, SwitchPattern.getBalanceWithSwitchPattern(savingsAccount), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Find Map Keys with Duplicate Values in Java](https://www.baeldung.com/java-map-find-keys-repeated-values)
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-maps-8</artifactId>
|
||||
<name>core-java-collections-maps-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>
|
||||
--add-opens java.base/java.util=ALL-UNNAMED
|
||||
</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.baeldung.map.valuetokeyset;
|
||||
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.mapping;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.SetMultimap;
|
||||
|
||||
public class ConvertMapKeyValueToMapValueKeySetUnitTest {
|
||||
|
||||
private static final Map<String, String> INPUT_MAP = Map.of(
|
||||
// @formatter:off
|
||||
"Kai", "Linux",
|
||||
"Eric", "MacOS",
|
||||
"Kevin", "Windows",
|
||||
"Liam", "MacOS",
|
||||
"David", "Linux",
|
||||
"Saajan", "Windows",
|
||||
"Loredana", "MacOS"
|
||||
// @formatter:on
|
||||
);
|
||||
|
||||
private static final Map<String, Set<String>> EXPECTED = Map.of(
|
||||
// @formatter:off
|
||||
"Linux", Set.of("Kai", "David"),
|
||||
"Windows", Set.of("Saajan", "Kevin"),
|
||||
"MacOS", Set.of("Eric", "Liam", "Loredana")
|
||||
// @formatter:on
|
||||
);
|
||||
|
||||
private static final Map<String, String> INPUT_MAP_WITH_NULLS = new HashMap<String, String>(INPUT_MAP) {{
|
||||
put("Tom", null);
|
||||
put("Jerry", null);
|
||||
put(null, null);
|
||||
}};
|
||||
|
||||
private static final Map<String, Set<String>> EXPECTED_WITH_NULLS = new HashMap<String, Set<String>>(EXPECTED) {{
|
||||
put(null, new HashSet<String>() {{
|
||||
add("Tom");
|
||||
add("Jerry");
|
||||
add(null);
|
||||
}});
|
||||
}};
|
||||
|
||||
public static <K, V> Map<V, Set<K>> transformMap(Map<K, V> input) {
|
||||
Map<V, Set<K>> resultMap = new HashMap<>();
|
||||
for (Map.Entry<K, V> entry : input.entrySet()) {
|
||||
if (!resultMap.containsKey(entry.getValue())) {
|
||||
resultMap.put(entry.getValue(), new HashSet<>());
|
||||
}
|
||||
resultMap.get(entry.getValue())
|
||||
.add(entry.getKey());
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingClassicLoopBasedSolution_thenGetExpectedResult() {
|
||||
Map<String, Set<String>> result = transformMap(INPUT_MAP);
|
||||
assertEquals(EXPECTED, result);
|
||||
|
||||
Map<String, Set<String>> result2 = transformMap(INPUT_MAP_WITH_NULLS);
|
||||
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingJava8StreamGroupingBy_thenGetExpectedResult() {
|
||||
Map<String, Set<String>> result = INPUT_MAP.entrySet()
|
||||
.stream()
|
||||
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet())));
|
||||
assertEquals(EXPECTED, result);
|
||||
|
||||
assertThrows(NullPointerException.class, () -> INPUT_MAP_WITH_NULLS.entrySet()
|
||||
.stream()
|
||||
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toSet()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingJava8ForEach_thenGetExpectedResult() {
|
||||
Map<String, Set<String>> result = new HashMap<>();
|
||||
INPUT_MAP.forEach((key, value) -> result.computeIfAbsent(value, k -> new HashSet<>())
|
||||
.add(key));
|
||||
assertEquals(EXPECTED, result);
|
||||
|
||||
Map<String, Set<String>> result2 = new HashMap<>();
|
||||
INPUT_MAP_WITH_NULLS.forEach((key, value) -> result2.computeIfAbsent(value, k -> new HashSet<>())
|
||||
.add(key));
|
||||
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingGuavaMultiMapCollector_thenGetExpectedResult() {
|
||||
Map<String, Set<String>> result = INPUT_MAP.entrySet()
|
||||
.stream()
|
||||
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
|
||||
assertEquals(EXPECTED, result);
|
||||
|
||||
Map<String, Set<String>> result2 = INPUT_MAP_WITH_NULLS.entrySet()
|
||||
.stream()
|
||||
.collect(collectingAndThen(Multimaps.toMultimap(Map.Entry::getValue, Map.Entry::getKey, HashMultimap::create), Multimaps::asMap));
|
||||
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingGuavaInvertFromAndForMap_thenGetExpectedResult() {
|
||||
SetMultimap<String, String> multiMap = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP), HashMultimap.create());
|
||||
Map<String, Set<String>> result = Multimaps.asMap(multiMap);
|
||||
assertEquals(EXPECTED, result);
|
||||
|
||||
SetMultimap<String, String> multiMapWithNulls = Multimaps.invertFrom(Multimaps.forMap(INPUT_MAP_WITH_NULLS), HashMultimap.create());
|
||||
Map<String, Set<String>> result2 = Multimaps.asMap(multiMapWithNulls);
|
||||
assertEquals(EXPECTED_WITH_NULLS, result2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,4 +6,5 @@
|
||||
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
|
||||
- [Cartesian Product of Any Number of Sets in Java](https://www.baeldung.com/java-cartesian-product-sets)
|
||||
- [How to Get Index of an Item in Java Set](https://www.baeldung.com/java-set-element-find-index)
|
||||
- [Check if an Element Is Present in a Set in Java](https://www.baeldung.com/java-set-membership)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.checkifpresentinset;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.collections4.SetUtils;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CheckIfPresentInSetUnitTest {
|
||||
|
||||
private static final Set<String> CITIES = new HashSet<>();
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
CITIES.add("Paris");
|
||||
CITIES.add("London");
|
||||
CITIES.add("Tokyo");
|
||||
CITIES.add("Tamassint");
|
||||
CITIES.add("New york");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingStreamAnyMatchMethod_thenCheck() {
|
||||
boolean isPresent = CITIES.stream()
|
||||
.anyMatch(city -> city.equals("London"));
|
||||
|
||||
assertThat(isPresent).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingStreamFilterMethod_thenCheck() {
|
||||
long resultCount = CITIES.stream()
|
||||
.filter(city -> city.equals("Tamassint"))
|
||||
.count();
|
||||
|
||||
assertThat(resultCount).isPositive();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingContainsMethod_thenCheck() {
|
||||
assertThat(CITIES.contains("London")).isTrue();
|
||||
assertThat(CITIES.contains("Madrid")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingCollectionsDisjointMethod_thenCheck() {
|
||||
boolean isPresent = !Collections.disjoint(CITIES, Collections.singleton("Paris"));
|
||||
|
||||
assertThat(isPresent).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingCollectionUtilsContainsAnyMethod_thenCheck() {
|
||||
boolean isPresent = CollectionUtils.containsAny(CITIES, Collections.singleton("Paris"));
|
||||
|
||||
assertThat(isPresent).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenASet_whenUsingSetUtilsIntersectionMethod_thenCheck() {
|
||||
Set<String> result = SetUtils.intersection(CITIES, Collections.singleton("Tamassint"));
|
||||
|
||||
assertThat(result).isNotEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -86,7 +86,7 @@
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
|
||||
<aspectjrt.version>1.9.20.1</aspectjrt.version>
|
||||
<cactoos.version>0.43</cactoos.version>
|
||||
<cactoos.version>0.55.0</cactoos.version>
|
||||
<ea-async.version>1.2.3</ea-async.version>
|
||||
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
|
||||
<aspectjtools.version>1.9.20.1</aspectjtools.version>
|
||||
|
||||
@@ -5,3 +5,4 @@ This module contains articles about converting between Java date and time object
|
||||
### Relevant Articles:
|
||||
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
||||
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
||||
- [Convert TemporalAccessor to LocalDate](https://www.baeldung.com/java-temporalaccessor-localdate-conversion)
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.TemporalAccessorToLocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAccessor;
|
||||
import java.time.temporal.TemporalQueries;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TemporalAccessorToLocalDateUnitTest {
|
||||
String dateString = "2022-03-28";
|
||||
TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_LOCAL_DATE.parse(dateString);
|
||||
|
||||
@Test
|
||||
public void givenTemporalAccessor_whenUsingLocalDateFrom_thenConvertToLocalDate() {
|
||||
LocalDate convertedDate = LocalDate.from(temporalAccessor);
|
||||
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTemporalAccessor_whenUsingTemporalQueries_thenConvertToLocalDate() {
|
||||
int year = temporalAccessor.query(TemporalQueries.localDate()).getYear();
|
||||
int month = temporalAccessor.query(TemporalQueries.localDate()).getMonthValue();
|
||||
int day = temporalAccessor.query(TemporalQueries.localDate()).getDayOfMonth();
|
||||
|
||||
LocalDate convertedDate = LocalDate.of(year, month, day);
|
||||
assertEquals(LocalDate.of(2022, 3, 28), convertedDate);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.openhtmlfiles;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.awt.*;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class OpenHtmlFilesUnitTest {
|
||||
public URL url;
|
||||
public String absolutePath;
|
||||
|
||||
public OpenHtmlFilesUnitTest() throws URISyntaxException {
|
||||
url = getClass().getResource("/test.html");
|
||||
assert url != null;
|
||||
File file = new File(url.toURI());
|
||||
if (!file.exists()) {
|
||||
fail();
|
||||
}
|
||||
absolutePath = file.getAbsolutePath();
|
||||
}
|
||||
/*
|
||||
@Test
|
||||
public void givenHtmlFile_whenUsingDesktopClass_thenOpenFileInDefaultBrowser() throws IOException {
|
||||
File htmlFile = new File(absolutePath);
|
||||
Desktop.getDesktop().browse(htmlFile.toURI());
|
||||
assertTrue(true);
|
||||
}
|
||||
*/
|
||||
@Test
|
||||
public void givenHtmlFile_whenUsingProcessBuilder_thenOpenFileInDefaultBrowser() throws IOException {
|
||||
ProcessBuilder pb;
|
||||
if (System.getProperty("os.name").toLowerCase().contains("win")) {
|
||||
pb = new ProcessBuilder("cmd.exe", "/c", "start", absolutePath);
|
||||
} else {
|
||||
pb = new ProcessBuilder("xdg-open", absolutePath);
|
||||
}
|
||||
pb.start();
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>
|
||||
|
||||
|
||||
</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>Hello dear friend</h1>
|
||||
</body>
|
||||
</html>
|
||||
@@ -11,3 +11,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
|
||||
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
|
||||
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
|
||||
- [Get a Path to a Resource in a Java JAR File](https://www.baeldung.com/java-get-path-resource-jar)
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.getpathtoresource;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class GetPathToResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenFile_whenClassUsed_thenGetResourcePath() {
|
||||
URL resourceUrl = GetPathToResourceUnitTest.class.getResource("/sampleText1.txt");
|
||||
assertNotNull(resourceUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenClassLoaderUsed_thenGetResourcePath() {
|
||||
URL resourceUrl = GetPathToResourceUnitTest.class.getClassLoader().getResource("sampleText1.txt");
|
||||
assertNotNull(resourceUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenPathUsed_thenGetResourcePath() throws Exception {
|
||||
Path resourcePath = Paths.get(Objects.requireNonNull(GetPathToResourceUnitTest.class.getResource("/sampleText1.txt")).toURI());
|
||||
assertNotNull(resourcePath);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,3 +13,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Read Multiple Inputs on the Same Line in Java](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
- [Java InputStream vs. InputStreamReader](https://www.baeldung.com/java-inputstream-vs-inputstreamreader)
|
||||
|
||||
+4
-4
@@ -11,28 +11,28 @@ public class UrlCheckerIntegrationTest {
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("https://httpbin.org/status/200");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/xyz");
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("https://httpbin.org/status/404");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
|
||||
int responseCode = tester.getResponseCodeForURL("https://httpbin.org/status/200");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com/xyz");
|
||||
int responseCode = tester.getResponseCodeForURL("https://httpbin.org/status/404");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import java.util.Map;
|
||||
|
||||
public class UseHashMapToConvertPhoneNumberInWordsToNumber {
|
||||
private static Map<String, Integer> multipliers = Map.of("double",2,
|
||||
"triple", 3,
|
||||
"quadruple", 4);
|
||||
private static Map<String, String> digits = Map.of("zero","1",
|
||||
"one", "1",
|
||||
"two", "2",
|
||||
"three", "3",
|
||||
"four", "4",
|
||||
"five", "5",
|
||||
"six", "6",
|
||||
"seven", "7",
|
||||
"eight", "8",
|
||||
"nine", "9");
|
||||
|
||||
|
||||
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
Integer currentMultiplier = null;
|
||||
String[] words = phoneNumberInWord.split(" ");
|
||||
|
||||
for (String word : words) {
|
||||
Integer multiplier = multipliers.get(word);
|
||||
if (multiplier != null) {
|
||||
if (currentMultiplier != null) {
|
||||
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
|
||||
}
|
||||
currentMultiplier = multiplier;
|
||||
} else {
|
||||
String digit = digits.get(word);
|
||||
if (digit == null) {
|
||||
throw new IllegalArgumentException("Invalid word: " + word);
|
||||
}
|
||||
output.append(digit.repeat(currentMultiplier != null ? currentMultiplier : 1));
|
||||
currentMultiplier = null;
|
||||
}
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
public class UseSwitchToConvertPhoneNumberInWordsToNumber {
|
||||
|
||||
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
Integer currentMultiplier = null;
|
||||
String[] words = phoneNumberInWord.split(" ");
|
||||
|
||||
for (String word : words) {
|
||||
Integer multiplier = getWordAsMultiplier(word);
|
||||
if (multiplier != null) {
|
||||
if (currentMultiplier != null) {
|
||||
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
|
||||
}
|
||||
currentMultiplier = multiplier;
|
||||
} else {
|
||||
output.append(getWordAsDigit(word).repeat(currentMultiplier != null ? currentMultiplier : 1));
|
||||
currentMultiplier = null;
|
||||
}
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
public static Integer getWordAsMultiplier(String word) {
|
||||
switch (word) {
|
||||
case "double":
|
||||
return 2;
|
||||
case "triple":
|
||||
return 3;
|
||||
case "quadruple":
|
||||
return 4;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getWordAsDigit(String word) {
|
||||
switch (word) {
|
||||
case "zero":
|
||||
return "0";
|
||||
case "one":
|
||||
return "1";
|
||||
case "two":
|
||||
return "2";
|
||||
case "three":
|
||||
return "3";
|
||||
case "four":
|
||||
return "4";
|
||||
case "five":
|
||||
return "5";
|
||||
case "six":
|
||||
return "6";
|
||||
case "seven":
|
||||
return "7";
|
||||
case "eight":
|
||||
return "8";
|
||||
case "nine":
|
||||
return "9";
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid word: " + word);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UseHashMapToConvertPhoneNumberInWordsToNumberUnitTest {
|
||||
|
||||
@Test
|
||||
void givenStringWithWhiteSpaces_WhenConvertPhoneNumberInWordsToNumber_ThenEquivalentNumber() {
|
||||
|
||||
assertEquals("5248888",
|
||||
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five two four quadruple eight"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringEndingWithConseutiveMultipliers_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five eight three double triple");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithInvalidWords_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
UseHashMapToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five eight three two four penta null eight");
|
||||
});
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UseSwitchToConvertPhoneNumberInWordsToNumberUnitTest {
|
||||
|
||||
@Test
|
||||
void givenStringWithWhiteSpaces_WhenConvertPhoneNumberInWordsToNumber_ThenEquivalentNumber() {
|
||||
|
||||
assertEquals("5248888",
|
||||
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five two four quadruple eight"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringEndingWithConseutiveMultipliers_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five eight three double triple");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringWithInvalidWords_WhenConvertPhoneNumberInWordsToNumber_ThenThrowException() {
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("five eight three two four penta null eight");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void givenString_WhenGetWordAsMultiplier_ThenEquivalentNumber() {
|
||||
assertEquals(2, UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.getWordAsMultiplier("double"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidString_WhenGetWordAsMultiplier_ThenReturnNull() {
|
||||
assertEquals(null, UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.getWordAsMultiplier("hexa"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_WhenMapIndividualDigits_ThenEquivalentNumber() {
|
||||
assertEquals("5",
|
||||
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.getWordAsDigit("five"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidString_WhenMapIndividualDigits_ThenThrowException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
UseSwitchToConvertPhoneNumberInWordsToNumber
|
||||
.convertPhoneNumberInWordsToNumber("penta");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,4 @@
|
||||
- [Get the Initials of a Name in Java](https://www.baeldung.com/java-shorten-name-initials)
|
||||
- [Normalizing the EOL Character in Java](https://www.baeldung.com/java-normalize-end-of-line-character)
|
||||
- [Converting UTF-8 to ISO-8859-1 in Java](https://www.baeldung.com/java-utf-8-iso-8859-1-conversion)
|
||||
- [Get Last n Characters From a String](https://www.baeldung.com/java-string-get-last-n-characters)
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.lastncharacters;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class LastNCharactersUnitTest {
|
||||
|
||||
private String s;
|
||||
private int n;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
s = "10-03-2024";
|
||||
n = 4;
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingIntStreamAsStreamSource_thenObtainLastNCharacters() {
|
||||
String result = s.chars()
|
||||
.mapToObj(c -> (char) c)
|
||||
.skip(s.length() - n)
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining());
|
||||
|
||||
assertThat(result).isEqualTo("2024");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingOneArgSubstringMethod_thenObtainLastNCharacters() {
|
||||
int beginIndex = s.length() - n;
|
||||
|
||||
assertThat(s.substring(beginIndex)).isEqualTo("2024");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingStreamOfCharactersAsSource_thenObtainLastNCharacters() {
|
||||
String result = Arrays.stream(ArrayUtils.toObject(s.toCharArray()))
|
||||
.skip(s.length() - n)
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining());
|
||||
|
||||
assertThat(result).isEqualTo("2024");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingStringUtilsRight_thenObtainLastNCharacters() {
|
||||
assertThat(StringUtils.right(s, n)).isEqualTo("2024");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingTwoArgSubstringMethod_thenObtainLastNCharacters() {
|
||||
int beginIndex = s.length() - n;
|
||||
String result = s.substring(beginIndex, s.length());
|
||||
|
||||
assertThat(result).isEqualTo("2024");
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@
|
||||
<module>core-java-collections-maps-2</module>
|
||||
<module>core-java-collections-maps-3</module>
|
||||
<module>core-java-collections-maps-7</module>
|
||||
<module>core-java-collections-maps-8</module>
|
||||
<module>core-java-compiler</module>
|
||||
<module>core-java-concurrency-2</module>
|
||||
<module>core-java-concurrency-advanced</module>
|
||||
|
||||
Reference in New Issue
Block a user