change method to return Optionals (#4464)

* change method to return Optionals

* add check for empty Optional
This commit is contained in:
Rajat Garg 2018-06-18 01:11:40 +05:30 committed by pauljervis
parent ee77a84225
commit 974637a273
2 changed files with 11 additions and 8 deletions

View File

@ -3,18 +3,18 @@ package com.baeldung.extension;
import com.google.common.io.Files;
import org.apache.commons.io.FilenameUtils;
import java.util.Optional;
public class Extension {
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
public String getExtensionByApacheCommonLib(String filename) {
return FilenameUtils.getExtension(filename);
}
public String getExtensionByStringHandling(String filename) {
String fileExtension = "";
if (filename.contains(".") && filename.lastIndexOf(".") != 0) {
fileExtension = filename.substring(filename.lastIndexOf(".") + 1);
}
return fileExtension;
public Optional<String> getExtensionByStringHandling(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
}
public String getExtensionByGuava(String filename) {

View File

@ -3,6 +3,8 @@ package com.baeldung.extension;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
public class ExtensionUnitTest {
private Extension extension = new Extension();
@ -16,8 +18,9 @@ public class ExtensionUnitTest {
@Test
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
String expectedExtension = "java";
String actualExtension = extension.getExtensionByStringHandling("Demo.java");
Assert.assertEquals(expectedExtension, actualExtension);
Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
Assert.assertTrue(actualExtension.isPresent());
actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext));
}
@Test