Hard to determine directly. No completely successful picture, primarily because the seeds out of which galaxies could have grown have not been clearly identified.
Gravity forces the lumps to collapse inward.
The compression of infall causes heating, which slows down the collapse if the heat is trapped inside. As any spinning object shrinks, it spins up. In a fluid, this can cause the formation of a spinning disk supported by its angular momentum. That is a galaxy forms, concentrating lumpy matter out of which stars and their planets form from the fragments.