Skip to content
Advertisement

Is there an analogue of put function of Map interface in List?

I have an ArrayList(input) of Node objects. Each node stores the information about how many times a sentence has been searched. The definition of Node class is –

class Node {
    String sentence;
    int count;

    Node(String st, int t) {
        sentence = st;
        count = t;
    }
}

the attribute sentence stores the sentence and count the number of times it was searched. Now I am given a sentence and I want to add it to this list with the updated count. The problem is the sentence may already be present in the list, in which case I just have to update the count attribute of that particular node by +1. In map interface it is easy by using –

map.put(sentence, map.getOrDefault(sentence, 0) + 1);

But how can I do it in List?

Advertisement

Answer

Like you I like to go object-oriented. A Map<String, Integer> isn’t satisfactory. We want to use your Node class.

I think that what you want is a Map<String, Node>. With it you can look up the node from the sentence. You may fit your Node class with a method to increment the count. And use computeIfAbsent() to create new nodes as necessary.

    Map<String, Node> map = new HashMap<>();
    
    map.computeIfAbsent("Cat", s -> new Node(s, 0)).incrementCount();
    map.computeIfAbsent("House", s -> new Node(s, 0)).incrementCount();
    map.computeIfAbsent("Cat", s -> new Node(s, 0)).incrementCount();
    
    System.out.println(map.values());

With a simple toString method in your class the output is:

[Cat: 2, House: 1]

I would also find it perfectly meaningful if your constructor takes only one argument, the sentence, and always sets count to 0. Or you may have both constructors.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement