Skip to content

Commit f11bd7d

Browse files
authored
file to map article (eugenp#11838)
* file to map article * add aggregateByKeys method
1 parent b38f226 commit f11bd7d

3 files changed

Lines changed: 155 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.baeldung.filetomap;
2+
3+
import java.io.BufferedReader;
4+
import java.io.FileReader;
5+
import java.io.IOException;
6+
import java.nio.file.Files;
7+
import java.nio.file.Paths;
8+
import java.util.HashMap;
9+
import java.util.List;
10+
import java.util.Map;
11+
import java.util.stream.Collectors;
12+
import java.util.stream.Stream;
13+
14+
public class FileToHashMap {
15+
16+
enum DupKeyOption {
17+
OVERWRITE, DISCARD
18+
}
19+
20+
public static Map<String, String> byBufferedReader(String filePath, DupKeyOption dupKeyOption) {
21+
HashMap<String, String> map = new HashMap<>();
22+
String line;
23+
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
24+
while ((line = reader.readLine()) != null) {
25+
String[] keyValuePair = line.split(":", 2);
26+
if (keyValuePair.length > 1) {
27+
String key = keyValuePair[0];
28+
String value = keyValuePair[1];
29+
if (DupKeyOption.OVERWRITE == dupKeyOption) {
30+
map.put(key, value);
31+
} else if (DupKeyOption.DISCARD == dupKeyOption) {
32+
map.putIfAbsent(key, value);
33+
}
34+
} else {
35+
System.out.println("No Key:Value found in line, ignoring: " + line);
36+
}
37+
}
38+
} catch (IOException e) {
39+
e.printStackTrace();
40+
}
41+
return map;
42+
}
43+
44+
public static Map<String, String> byStream(String filePath, DupKeyOption dupKeyOption) {
45+
Map<String, String> map = new HashMap<>();
46+
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
47+
lines.filter(line -> line.contains(":"))
48+
.forEach(line -> {
49+
String[] keyValuePair = line.split(":", 2);
50+
String key = keyValuePair[0];
51+
String value = keyValuePair[1];
52+
if (DupKeyOption.OVERWRITE == dupKeyOption) {
53+
map.put(key, value);
54+
} else if (DupKeyOption.DISCARD == dupKeyOption) {
55+
map.putIfAbsent(key, value);
56+
}
57+
});
58+
} catch (IOException e) {
59+
e.printStackTrace();
60+
}
61+
return map;
62+
}
63+
64+
public static Map<String, List<String>> aggregateByKeys(String filePath) {
65+
Map<String, List<String>> map = new HashMap<>();
66+
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
67+
lines.filter(line -> line.contains(":"))
68+
.forEach(line -> {
69+
String[] keyValuePair = line.split(":", 2);
70+
String key = keyValuePair[0];
71+
String value = keyValuePair[1];
72+
if (map.containsKey(key)) {
73+
map.get(key).add(value);
74+
} else {
75+
map.put(key, Stream.of(value).collect(Collectors.toList()));
76+
}
77+
});
78+
} catch (IOException e) {
79+
e.printStackTrace();
80+
}
81+
return map;
82+
}
83+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.baeldung.filetomap;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import java.net.URISyntaxException;
7+
import java.nio.file.Paths;
8+
import java.util.Arrays;
9+
import java.util.List;
10+
import java.util.Map;
11+
import java.util.stream.Collectors;
12+
import java.util.stream.Stream;
13+
14+
import static org.assertj.core.api.Assertions.assertThat;
15+
16+
public class FileToHashMapUnitTest {
17+
18+
private String filePath;
19+
20+
private static final Map<String, String> EXPECTED_MAP_DISCARD = Stream.of(new String[][]{
21+
{"title", "The Lord of the Rings: The Return of the King"},
22+
{"director", "Peter Jackson"},
23+
{"actor", "Sean Astin"}
24+
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
25+
26+
private static final Map<String, String> EXPECTED_MAP_OVERWRITE = Stream.of(new String[][]{
27+
{"title", "The Lord of the Rings: The Return of the King"},
28+
{"director", "Peter Jackson"},
29+
{"actor", "Ian McKellen"}
30+
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
31+
32+
private static final Map<String, List<String>> EXPECTED_MAP_AGGREGATE = Stream.of(new String[][]{
33+
{"title", "The Lord of the Rings: The Return of the King"},
34+
{"director", "Peter Jackson"},
35+
{"actor", "Sean Astin", "Ian McKellen"}
36+
}).collect(Collectors.toMap(arr -> arr[0], arr -> Arrays.asList(Arrays.copyOfRange(arr, 1, arr.length))));
37+
38+
@Before
39+
public void setPath() throws URISyntaxException {
40+
if (filePath == null) {
41+
filePath = Paths.get(ClassLoader.getSystemResource("filetomap/theLordOfRings.txt").toURI()).toString();
42+
}
43+
}
44+
45+
@Test
46+
public void givenInputFile_whenInvokeByBufferedReaderPriorToJava8_shouldGetExpectedMap() {
47+
Map<String, String> mapOverwrite = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
48+
Map<String, String> mapDiscard = FileToHashMap.byBufferedReader(filePath, FileToHashMap.DupKeyOption.DISCARD);
49+
assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
50+
assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
51+
}
52+
53+
@Test
54+
public void givenInputFile_whenInvokeByStream_shouldGetExpectedMap() {
55+
Map<String, String> mapOverwrite = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.OVERWRITE);
56+
Map<String, String> mapDiscard = FileToHashMap.byStream(filePath, FileToHashMap.DupKeyOption.DISCARD);
57+
assertThat(mapOverwrite).isEqualTo(EXPECTED_MAP_OVERWRITE);
58+
assertThat(mapDiscard).isEqualTo(EXPECTED_MAP_DISCARD);
59+
}
60+
61+
@Test
62+
public void givenInputFile_whenInvokeAggregateByKeys_shouldGetExpectedMap() {
63+
Map<String, List<String>> mapAgg = FileToHashMap.aggregateByKeys(filePath);
64+
assertThat(mapAgg).isEqualTo(EXPECTED_MAP_AGGREGATE);
65+
}
66+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
title:The Lord of the Rings: The Return of the King
2+
director:Peter Jackson
3+
actor:Sean Astin
4+
actor:Ian McKellen
5+
Gandalf and Aragorn lead the World of Men against Sauron's
6+
army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.

0 commit comments

Comments
 (0)