Java 8 - Best way to transform a list: map or foreach?

前端 未结 8 1860
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 07:01

I have a list myListToParse where I want to filter the elements and apply a method on each element, and add the result in another list myFinalList.

8条回答
  •  失恋的感觉
    2020-12-07 07:39

    If you use Eclipse Collections you can use the collectIf() method.

    MutableList source =
        Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);
    
    MutableList result = source.collectIf(Objects::nonNull, String::valueOf);
    
    Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);
    

    It evaluates eagerly and should be a bit faster than using a Stream.

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题