Java, Python, Quick solutions, Uncategorized

How to solve: pick elements from one list, that indexes are stored in second list

Today I am going to show you how to create a list combined with those elements from one list, that have indexes collected in the second list. For my example I will use python, because I have a little contact with it recently at my work.

def main():
    x = ['a', 'b', 'c', 'd', 'e']
    y = [1, 2, 3]
    z = [x[_] for _ in y]
    print(z)


if __name__ == "__main__":
    main()

Script presented above solves exactly the issue, which was presented in the topic.  You may ask, what underscore (‘_’) sign means in this case. It represents each and every element in the list and helps to iterate over them without necessity of describing it in a direct way. It can be substituted with another variable crated in place by parser. The same thing is achieved in stream API of Java 8 with lambdas, but single underscore sign is not allowed it this case:

IntStream.range(1, 4).map(_a -> _a * 2).forEach(System.out::print);

Python code should print list containing three elements like below:

[‘b’, ‘c’, ‘d’]

Mockito, Quick solutions

How to solve: mocking chained calls

I have met this issue several times, so I decided to give the simplest solution to you. You have probably had a situation, when you need to return one object, but it demanded mocking each and every object in the middle. You can avoid that by adding parameter to you mocked object like:

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Client elasticSearchClient;

@Mock
private ClusterHealthRequestBuilder healthRequestBuilder;

Currently you can use when() as presented below:

when(elasticSearchClient.admin().cluster().prepareHealth().setWaitForStatus(any())).thenReturn(healthRequestBuilder);

instead of mocking AdminClient, ClusterAdminClient and ClusterHealthRequestBuilder by hand:

@Mock
ptivate AdminClient admin;
@Mock
private ClusterAdminClient cluster;
@Mock
private ClusterHealthRequestBuilder clusterHealthRequestBuilder;

@Before
public void setUp() {
    when(elasticSearchClient.admin()).thenReturn(admin);
    when(admin.cluster()).thenReturn(cluster);
    when(cluster.prepareHealth()).thenReturn(clusterHealthRequestBuilder);
    when(clusterHealthRequestBuilder.setWaitForStatus(any())).thenReturn(healthRequestBuilder);
}