I am trying to merge line toghether to create data for my programm. Curently the merging part of the String
s in the ArrayList
's buffer works well but when I output the content of the Map
I am getting another of the String
as they were in the ArrayList
's buffer.
Is there any way to keep the order of String
s as they were in the ArrayList
buffer?
Output:
Nathan Marcus Adler
[04:43, 05:43, 12:11, 12:41, 19:11, 19:41]
Dukes of Bedford
[04:56, 05:56, 12:24, 12:54, 19:24, 19:54]
Prince Albert
[04:48, 05:48, 12:16, 12:46, 19:16, 19:46]
Joseph Addison
[04:41, 05:41, 12:08, 12:38, 19:08, 19:38]
William Baker
[04:52, 05:52, 12:20, 12:50, 19:20, 19:50]
The ouput should looks as this:
Joseph Addison
[04:41, 05:41, 12:08, 12:38, 19:08, 19:38]
Nathan Marcus Adler
[04:43, 05:43, 12:11, 12:41, 19:11, 19:41]
Prince Albert
[04:48, 05:48, 12:16, 12:46, 19:16, 19:46]
William Baker
[04:52, 05:52, 12:20, 12:50, 19:20, 19:50]
Dukes of Bedford
[04:56, 05:56, 12:24, 12:54, 19:24, 19:54]
Code:
public static void main(String[] args) {
ArrayList<String> buffer = new ArrayList<String>();
buffer.add("Joseph Addison 04:41 05:41");
buffer.add("Nathan Marcus Adler 04:43 05:43");
buffer.add("Prince Albert 04:48 05:48");
buffer.add("William Baker 04:52 05:52");
buffer.add("Dukes of Bedford 04:56 05:56");
buffer.add("Joseph Addison 12:08 12:38 ");
buffer.add("Nathan Marcus Adler 12:11 12:41");
buffer.add("Prince Albert 12:16 12:46");
buffer.add("William Baker 12:20 12:50");
buffer.add("Dukes of Bedford 12:24 12:54");
buffer.add("Joseph Addison 19:08 19:38");
buffer.add("Nathan Marcus Adler 19:11 19:41");
buffer.add("Prince Albert 19:16 19:46");
buffer.add("William Baker 19:20 19:50");
buffer.add("Dukes of Bedford 19:24 19:54");
Map<String, List<String>> map = new HashMap<>();
ArrayList<PlaceTime> list = new ArrayList<PlaceTime>();
for (String element : buffer) {
PlaceTime part = new PlaceTime(element);
list.add(part);
}
for (PlaceTime t : list) {
if (map.containsKey(t.getPlace())) {
// If the map already contains an entry for the place, add the
// times to the array
map.get(t.getPlace()).addAll(t.getTimes());
} else {
// Map does not contain entry for place, create a new entry
map.put(t.getPlace(), t.getTimes());
}
}
// Print out contents of map
for (Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
System.out.println("Test");
}
PlaceTime class:
public class PlaceTime {
StringBuilder place = new StringBuilder();
List<String> times = new ArrayList<>();;
public PlaceTime(String placeTime) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
for (String i:placeTime.split(" ")) {
try {
dateFormat.parse(i);
//No exception, add as time
times.add(i);
} catch (Exception e) {
//Exception, add as place name
place.append(i).append(" ");
}
}
}
public String getPlace() {
return place.toString();
}
public List<String> getTimes() {
return this.times;
}
}