How to randomize two ArrayLists in the same fashion?

Use Collections.shuffle() twice, with two Random objects initialized with the same seed: long seed = System.nanoTime(); Collections.shuffle(fileList, new Random(seed)); Collections.shuffle(imgList, new Random(seed)); Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

How to print out all the elements of a List in Java?

The following is compact and avoids the loop in your example code (and gives you nice commas): System.out.println(Arrays.toString(list.toArray())); However, as others have pointed out, if you don’t have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you’re observing. This is true whether they’re … Read more

When to use a linked list over an array/array list?

Linked lists are preferable over arrays when: you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical) you don’t know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big you don’t need … Read more

Why is it string.join(list) instead of list.join(string)?

It’s because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the “joiner” must be strings. For example: ‘_’.join([‘welcome’, ‘to’, ‘stack’, ‘overflow’]) ‘_’.join((‘welcome’, ‘to’, ‘stack’, ‘overflow’)) ‘welcome_to_stack_overflow’ Using something other than strings will raise the following error: TypeError: sequence item 0: expected str instance, int found

List comprehension vs generator expression’s weird timeit results?

Expanding on Paulo’s answer, generator expressions are often slower than list comprehensions because of the overhead of function calls. In this case, the short-circuiting behavior of in offsets that slowness if the item is found fairly early, but otherwise, the pattern holds. I ran a simple script through the profiler for a more detailed analysis. … Read more