Simply create an EditorCollapseAll.cs script in Assets/Editor folder of your project and paste the above code in it.

Collapsing Hierarchy View
To collapse all GameObjects in the currently active Hierarchy view, either use the GameObject menu or right click a GameObject and select "Collapse All".

Collapsing Project View
To collapse all folders in Project view, either use the Assets menu or right click an asset and select "Collapse Folders". Note that folders containing the selected assets will not be collapsed.

The code actually simulates the same behaviour programmatically, only that it selects all the root folders and collapses them all at once, so that you won't have to alt-click them all one by one (can be useful when you have many root folders).