私の答えは、データセットを既に並べ替えており、それらが正しい順序になっていることを前提としています。
public class SubsetPrinter
{
private static final String DELIMITER = ", ";
private static final String NEWLINE = System.getProperty("line.separator");
public static String printSubsets(Map<String, List<String>> elements)
{
List<String> lines = new ArrayList<String>();
for (Map.Entry<String, List<String>> entry : elements.entrySet())
{
for (String sub : entry.getValue())
{
String line = getLine(elements, entry.getKey(), sub);
if (!lines.contains(line))
{
lines.add(line);
}
}
}
return asString(lines);
}
private static String getLine(Map<String, List<String>> elements, String element, String sub)
{
StringBuilder line = null;
for (Map.Entry<String, List<String>> entry : elements.entrySet())
{
if (line == null)
{
line = new StringBuilder();
}
else
{
line.append(DELIMITER);
}
if (entry.getKey().equals(element))
{
line.append(sub);
}
else
{
line.append(entry.getValue().get(0)); // appends the first
}
}
return line.toString();
}
private static String asString(List<String> lines)
{
StringBuilder sb = null;
for (String line : lines)
{
if (sb == null)
{
sb = new StringBuilder();
}
else
{
sb.append(NEWLINE);
}
sb.append(line);
}
return sb.toString();
}
}
そして、テストは次のとおりです。
private Map<String, List<String>> getDataSet1()
{
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> subsetA = Arrays.asList( new String[] { "a1", "a2", "a3" } );
List<String> subsetB = Arrays.asList( new String[] { "b1", "b2" } );
List<String> subsetC = Arrays.asList( new String[] { "c1", "c2", "c3" } );
map.put("A", subsetA);
map.put("B", subsetB);
map.put("C", subsetC);
return map;
}
@Test
public void testPrintSubsets()
{
Map<String, List<String>> elements = getDataSet1();
String output = SubsetPrinter.printSubsets(elements);
System.out.println(output);
}
出力:
a1, b1, c1
a2, b1, c1
a3, b1, c1
a1, b2, c1
a1, b1, c2
a1, b1, c3