Java 8 lambda get and remove element from list

后端 未结 12 1606
说谎
说谎 2020-12-08 12:47

Given a list of elements, I want to get the element with a given property and remove it from the list. The best solution I found is:

Produce         


        
12条回答
  •  情书的邮戳
    2020-12-08 13:07

    With Eclipse Collections you can use detectIndex along with remove(int) on any java.util.List.

    List integers = Lists.mutable.with(1, 2, 3, 4, 5);
    int index = Iterate.detectIndex(integers, i -> i > 2);
    if (index > -1) {
        integers.remove(index);
    }
    
    Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
    

    If you use the MutableList type from Eclipse Collections, you can call the detectIndex method directly on the list.

    MutableList integers = Lists.mutable.with(1, 2, 3, 4, 5);
    int index = integers.detectIndex(i -> i > 2);
    if (index > -1) {
        integers.remove(index);
    }
    
    Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
    

    Note: I am a committer for Eclipse Collections

提交回复
热议问题