使用 java 流获取逗号分隔的字符串

2022-09-04 07:20:04

我有以下使用java的代码。Stream

我正在尝试获取函数以构建一个值字符串:在这种情况下为“a,b”。但是,输出(在本例中)始终为“b”。separatedByComma

有人可以透露一些光明吗?

@Test
public void testJoin() {
    List<MOccS> occList = new ArrayList<> (  );
    MOccS mOccS = new MOccS ();
    mOccS.setOccSCd ( "1" );
    mOccS.setOccSNm ( "a" );
    occList.add ( mOccS );

    MOccS mOccS2 = new MOccS ();
    mOccS2.setOccSCd ( "2" );
    mOccS2.setOccSNm ( "b" );
    occList.add ( mOccS2 );


    List<String> strings = new ArrayList<> (  );
    strings.add ( "1" );
    strings.add ( "2" );

    String separatedByComma = "";
    for(String word: strings) {
        separatedByComma = occList.stream ()
                                  .filter ( occ -> word.equalsIgnoreCase ( occ.getOccSCd () ) )         
                                  .map ( occ -> occ.getOccSNm () )
                                  .collect ( Collectors.joining ( "," ) );
     }

     System.out.println (separatedByComma);
}


class MOccS{
    String occSCd;
    String occSNm;
    ...
    getter/setter
    ...
}

答案 1

循环的每次迭代都会覆盖 的值。第一次迭代为其分配“a”,第二次迭代将其替换为“b”。forseparatedByCommaString

您应该在 的元素上,以便将每个元素匹配的 s 联接到单个输出中:StreamstringsListStringString

String separatedByComma = 
    strings.stream()
           .flatMap(word -> occList.stream()
                                   .filter(occ -> word.equalsIgnoreCase (occ.getOccSCd()))
                                   .map (occ -> occ.getOccSNm()))
           .collect(Collectors.joining (","));

输出:

a,b

答案 2

在循环中,您覆盖了变量。for(String word: strings)separatedByComma


推荐