file to map article (#11838)

* file to map article

* add aggregateByKeys method
This commit is contained in:
Kai Yuan 2022-03-01 02:44:16 +01:00 committed by GitHub
parent be0e55765c
commit 5582611107
3 changed files with 155 additions and 0 deletions

View File

@ -0,0 +1,83 @@
package com.baeldung.filetomap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileToHashMap {
enum DupKeyOption {
OVERWRITE, DISCARD
}
public static Map<String, String> byBufferedReader(String filePath, DupKeyOption dupKeyOption) {
HashMap<String, String> map = new HashMap<>();
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
while ((line = reader.readLine()) != null) {
String[] keyValuePair = line.split(":", 2);
if (keyValuePair.length > 1) {
String key = keyValuePair[0];
String value = keyValuePair[1];
if (DupKeyOption.OVERWRITE == dupKeyOption) {
map.put(key, value);
} else if (DupKeyOption.DISCARD == dupKeyOption) {
map.putIfAbsent(key, value);
}
} else {
System.out.println("No Key:Value found in line, ignoring: " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
public static Map<String, String> byStream(String filePath, DupKeyOption dupKeyOption) {
Map<String, String> map = new HashMap<>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.filter(line -> line.contains(":"))
.forEach(line -> {
String[] keyValuePair = line.split(":", 2);
String key = keyValuePair[0];
String value = keyValuePair[1];
if (DupKeyOption.OVERWRITE == dupKeyOption) {
map.put(key, value);
} else if (DupKeyOption.DISCARD == dupKeyOption) {
map.putIfAbsent(key, value);
}
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
public static Map<String, List<String>> aggregateByKeys(String filePath) {
Map<String, List<String>> map = new HashMap<>();
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.filter(line -> line.contains(":"))
.forEach(line -> {
String[] keyValuePair = line.split(":", 2);
String key = keyValuePair[0];
String value = keyValuePair[1];
if (map.containsKey(key)) {
map.get(key).add(value);
} else {
map.put(key, Stream.of(value).collect(Collectors.toList()));
}
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.filetomap;
import org.junit.Before;
import org.junit.Test;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class FileToHashMapUnitTest {
private String filePath;
private static final Map<String, String> EXPECTED_MAP_DISCARD = Stream.of(new String[][]{
{"title", "The Lord of the Rings: The Return of the King"},
{"director", "Peter Jackson"},
{"actor", "Sean Astin"}
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
private static final Map<String, String> EXPECTED_MAP_OVERWRITE = Stream.of(new String[][]{
{"title", "The Lord of the Rings: The Return of the King"},
{"director", "Peter Jackson"},
{"actor", "Ian McKellen"}
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
private static final Map<String, List<String>> EXPECTED_MAP_AGGREGATE = Stream.of(new String[][]{
{"title", "The Lord of the Rings: The Return of the King"},
{"director", "Peter Jackson"},
{"actor", "Sean Astin", "Ian McKellen"}
}).collect(Collectors.toMap(arr -> arr[0], arr -> Arrays.asList(Arrays.copyOfRange(arr, 1, arr.length))));
@Before
public void setPath() throws URISyntaxException {
if (filePath == null) {
filePath = Paths.get(ClassLoader.getSystemResource("filetomap/theLordOfRings.txt").toURI()).toString();
}
}
@Test
public void givenInputFile_whenInvokeByBufferedReaderPriorToJava8_shouldGetExpectedMap() {
Map<String, String> mapOverwrite = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
Map<String, String> mapDiscard = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.DISCARD);
assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
}
@Test
public void givenInputFile_whenInvokeByStream_shouldGetExpectedMap() {
Map<String, String> mapOverwrite = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
Map<String, String> mapDiscard = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.DISCARD);
assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
}
@Test
public void givenInputFile_whenInvokeAggregateByKeys_shouldGetExpectedMap() {
Map<String, List<String>> mapAgg = FileToHashMap.aggregateByKeys(filePath);
assertThat(mapAgg).isEqualTo(EXPECTED_MAP_AGGREGATE);
}
}

View File

@ -0,0 +1,6 @@
title:The Lord of the Rings: The Return of the King
director:Peter Jackson
actor:Sean Astin
actor:Ian McKellen
Gandalf and Aragorn lead the World of Men against Sauron's
army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.