我从这组代码中获得了不需要的额外列。我只想为不匹配的数据添加0,但它为我提供了所有数据列并分别指示0和1。
for ( int i = 0 ; i < GST.size(); i++)
{
for ( String FLD: GHA.keySet() )
{
if ( GHA.get(FLD).containsKey( GST.get(i) ) )
GHAS.get(FLD).append("1,");
else //these 2 lines
GHAS.get(FLD).append("0,"); //these 2 lines
}
}
String resultString = stringWriter.toString();
for ( String FLD: GHA.keySet() )
resultString += FLD+ "," +GHAS.get(FLD).toString() + System.getProperty("line.separator");
以下是此代码的输出
row1, 0, 0, 0, 1, 0
row2, 0, 0, 0, 0, 0
row3, 0, 0, 0, 0, 1
row4, 0, 0, 1, 0, 0
row5, 0, 0, 0, 0, 0
如果没有我已经指出过的2行
row1, 1,
row2,
row3, 1,
row4, 1,
row5,
我想要的输出是
row1, 1,
row2, 0,
row3, 1,
row4, 1,
row5, 0,
答案 0 :(得分:3)
for ( String FLD: GHA.keySet() )
{
boolean appended = false;
for ( int i = 0 ; i < GST.size(); i++)
{
if ( GHA.get(FLD).containsKey( GST.get(i) ) ) {
GHAS.get(FLD).append("1,");
appended = true;
// optionally break here if you don't want multiple 1s
}
}
if (!appended) {
GHAS.get(FLD).append("0,"); // instead of those 2 lines
}
}
String resultString = stringWriter.toString();
for ( String FLD: GHA.keySet() )
resultString += FLD+ "," +GHAS.get(FLD).toString() + System.getProperty("line.separator");