EzDevInfo.com

collections interview questions

Top collections frequently asked interview questions

Sort a Map by values (Java)

I am relatively new to Java, and often find that I need to sort a Map<Key, Value> on the values. Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key. Is there an easier way?


Source: (StackOverflow)

When to use LinkedList over ArrayList?

I've always been one to simply use:

List<String> names = new ArrayList<String>();

I use the interface as the type name for portability, so that when I ask questions such as these I can rework my code.

When should LinkedList be used over ArrayList and vice-versa?


Source: (StackOverflow)

Advertisements

Initialization of an ArrayList in one line

I want to create a list of options for testing purposes. At first, I did this:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?


Source: (StackOverflow)

Why there is no ConcurrentHashSet against ConcurrentHashMap

HashSet is based on HashMap.

If we look at HashSet<E> implementation, everything is been managed under HashMap<E,Object>.

<E> is used as a key of HashMap.

And we know that HashMap is not thread safe. That is why we have ConcurrentHashMap in Java.

Based on this, I am confused that why we don't have a ConcurrentHashSet which should be based on the ConcurrentHashMap?

Is there anything else that I am missing? I need to use Set in a multi-threaded environment.

Also, If I want to create my own ConcurrentHashSet can I achieve it by just replacing the HashMap to ConcurrentHashMap and leaving the rest as is?


Source: (StackOverflow)

Most efficient way to increment a Map value in Java

I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.

Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found.

In Perl, incrementing such a value would be trivially easy:

$map{$word}++;

But in Java, it's much more complicated. Here the way I'm currently doing it:

int count = map.containsKey(word) ? map.get(word) : 0;
map.put(word, count + 1);

Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead?

Update: I've done a test of several of the answers. See below.


Source: (StackOverflow)

Difference between and in Java

What is the difference between List<? super T> and List<? extends T> ?

I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super T> allows.

I want to know the difference.


Source: (StackOverflow)

Retrieving a List from a java.util.stream.Stream in Java8

I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach so far:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);

Examples on the net did not answer my question because they stop without generating a new result list. There must be a more concise way. I would have expected, that the Stream class has methods as toList(), toSet(), ...

Is there a way that the variables targetLongList can be directly be assigned by the third line?


Source: (StackOverflow)

Java Ordered Map

In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?

So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:

OrderedMap<Integer, String> om = new OrderedMap<>();
om.put(0, "Zero");
om.put(7, "Seven");

String o = om.get(7); // o is "Seven"
List<Integer> keys = om.getKeys();
List<String> values = om.getValues();

for(int i = 0; i < keys.size(); i++)
{
    Integer key = keys.get(i);
    String value = values.get(i);
    Assert(om.get(key) == value);
}

Source: (StackOverflow)

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

I am trying to figure out when and why to use a Dictionary or a HashTable. I have done a bit of a search on here and have found people talking about the generic advantages of the Dictionary which I totally agree with, which leads the boxing and unboxing advantage for a slight performance gain.

But I have also read the Dictionary will not always return the objects in the order they are inserted, thing it is sorted. Where as a HashTable will. As I understand it this leads to the HashTable being far faster for some situations.

My question is really, what might those situations be? Am I just wrong in my assumptions above? What situations might you use to choose one above the other, (yes the last one is a bit ambiguous).


Source: (StackOverflow)

Why doesn't java.util.Set have get(int index)?

I'm sure there's a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get() method?

It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item from it.

If I know I want the first item, I can use set.iterator().next(), but otherwise it seems I have to cast to an Array to retrieve an item at a specific index?

What are the appropriate ways of retrieving data from a set? (other than using an iterator)

I'm sure the fact that it's excluded from the API means there's a good reason for not doing this -- could someone please enlighten me?

EDIT: Some extremely great answers here, and a few saying "more context". The specific scenario was a dbUnit test, where I could reasonably assert that the returned set from a query had only 1 item, and I was trying to access that item.

However, the question is more valid without the scenario, as it remains more focussed:

What's the difference between set and list.

Thanks to all for the fantastic answers below.


Source: (StackOverflow)

HashSet vs. List performance

It's clear that a search performance of the generic HashSet<T> class is higher than of the generic List<T> class. Just compare the hash-based key with the linear approach in the List<T> class.

However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the HashSet<T>.

My question: where is the break-even?

To simplify the scenario (and to be fair) let's assume that the List<T> class uses the element's Equals() method to identify an item.


Source: (StackOverflow)

How to convert List to int[] in Java?

This is similar to this question: How to convert int[] to Integer[] in Java?

I'm new to Java. How can i convert a List<Integer> to int[] in Java? I'm confused because List.toArray() actually returns an Object[], which can be cast to nether Integer[] or int[].

Right now I'm using a loop to do so:

int[] toIntArray(List<Integer> list){
  int[] ret = new int[list.size()];
  for(int i = 0;i < ret.length;i++)
    ret[i] = list.get(i);
  return ret;
}

I'm sure there's a better way to do this.


Source: (StackOverflow)

How to directly initialize a HashMap (in a literal way)? [duplicate]

This question already has an answer here:

Is there some way of initializing a Java HashMap like this?:

Map<String,String> test = 
    new HashMap<String, String>{"test":"test","test":"test"};

What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastet way to put some "final/static" values in a map that never change and are known in advance when crerating the Map.


Source: (StackOverflow)

Easiest way to convert a List to a Set? - Java

Easiest way to convert a List to a Set? - In Java


Source: (StackOverflow)

In Java, How to Easily Convert an Array to a Set

I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:

java.util.Arrays.asList(Object[] a);

Any ideas?


Source: (StackOverflow)