For example, Map<String*, Integer> map = new TreeMap<String, Integer>(); , where * can I put < <String,String>, Integer > for example?

2. What are singleton collections for? The first time I hear. Google gives little information.

  • one
    The essence of a singleton collection, as a rule, comes down to redefining the methods of the collection interface that are optimized for one element as much as possible. There are still empty collections implemented in a similar way. The first one is used to transfer only one value, also often seen the following construction List <SomeClass> list = new ArrayList <> (Collections.singleton (someClass)); those. initialize the collection immediately with a single value. The second one is used, as a rule, to avoid null-s . I. Perevoz

1 answer 1

Depends on the specific implementation of the Map . For TreeMap , the key requirement is the implementation of the Comparable interface. Accordingly, you can define your own class, which has two fields of type String and implements Comparable , and then use objects of this class as a key. It is even easier to use HashMap instead of TreeMap . The HashMap key can be any hash object, so you can use, for example, a List containing a couple of lines.

 List<String> key1 = new ArrayList<>(); key1.add("qqq"); key1.add("www"); List<String> key2 = new ArrayList<>(); key2.add("eee"); key2.add("rrr"); Map<List, Integer> map = new HashMap<>(); map.put(key1, 1); map.put(key2, 2); 

The second part of the question is too general. And as the definition of "single-element collection" is too vague, and the scope of its application is very extensive. For example, some method waits for a collection as an argument, and you only need to pass one element.

 List<String> list = new ArrayList<>(); list.add("abc"); list.add(null); list.add("def"); list.removeAll(Collections.singletonList(null));