ここでは、Java 8つのストリーム使用したバージョンです:
// Initial list
public class AttributeValue {
String id;
String attribute;
String attributeValue;
AttributeValue(String id, String attribute, String attributeValue) {
this.id = id;
this.attribute = attribute;
this.attributeValue = attributeValue;
}
@Override
public String toString() {
return "{" + id + "," + attribute + "," + attributeValue + "}";
}
// ommiting equals() and hashCodes() methods for simplification
}
// final list
public class Record {
String id;
List<String> attributes;
List<String> attributeValues;
Record(String id, List<String> attributes, List<String> attributeValues) {
this.id = id;
this.attributes = attributes;
this.attributeValues = attributeValues;
}
@Override
public String toString() {
return "{{" + id + "},"
+ attributes.stream().collect(Collectors.joining(",", "{", "}")) + ","
+ attributeValues.stream().collect(Collectors.joining(",", "{", "}")) + "}";
}
// ommiting equals() and hashCodes() methods for simplification
}
private List<Record> transform(List<AttributeValue> values) {
return values.stream()
.collect(Collectors.groupingBy(value -> value.id, LinkedHashMap::new, Collectors.toList()))
.entrySet().stream()
.map(pair -> new Record(
pair.getKey(),
pair.getValue().stream().map(value -> value.attribute).collect(Collectors.toList()),
pair.getValue().stream().map(value -> value.attributeValue).collect(Collectors.toList())
))
.collect(Collectors.toList());
}
そして流暢さのためにjunit5とassertjを使用してユニットテスト: `Stream.map()`で
@Test
void parse_a_van_page_with_empty_json_data() throws Exception {
List<AttributeValue> initial = Arrays.asList(
new AttributeValue("1-a12-abc", "firstname", "john"),
new AttributeValue("2-a12-abc", "firstname", "tom"),
new AttributeValue("1-a12-abc", "lastname", "doe"),
new AttributeValue("3-a22-abc", "city", "Delhi")
);
List<Record> expected = Arrays.asList(
new Record("1-a12-abc", Arrays.asList("firstname", "lastname"), Arrays.asList("john", "doe")),
new Record("2-a12-abc", Collections.singletonList("firstname"), Collections.singletonList("tom")),
new Record("3-a22-abc", Collections.singletonList("city"), Collections.singletonList("Delhi"))
);
assertThat(transform(initial)).containsAll(expected);
// Some printing
System.out.println("initial: ");
initial.forEach(System.out::println);
System.out.println("expected: ");
expected.forEach(System.out::println);
}
見て、 'ストリームを.collect() '、' Collectors.groupingBy() '。あなたが立ち往生すると、あなたは戻ってきて詳細を聞くことができます。しかし、誰かがあなた自身の努力を示すことなく完全なソリューションを提供するとは思わないでください。 –