exact java solution recreated in scala