Count number of items with property

后端 未结 10 2537
不思量自难忘°
不思量自难忘° 2021-02-13 12:18

I have list List where Custom is like

class Custom{
    public int id;
    public String name;
}

How to

10条回答
  •  你的背包
    2021-02-13 12:50

    The way it is defined now will always require looping over the list.

    Creating a secondary index with a map of names to list of ids is one good idea.

    One more option would be to make sure the list is ordered by name, in which case all "Tom"s would be stored next to each other. Then you could find the fist "Tom" in O(log(n)) time with a binary search, and just keep counting from there until you reach a non-"Tom" or end of the list. The insert operation would have O(n) complexity as you need to move all elements after the insert location by one position, so consider this carefully :-)

提交回复
热议问题