In addition to Tom Constable’s helpful notes. I also recommend Paul Copan’s book “Is God a Moral Monster?: Making Sense of the Old Testament God.”
Here is an excerpt from “Is God a Moral Monster?” that deals with Numbers 31.
The Midianites (Numbers 31)
As with Israel’s lifelong enemies, the Amalekites (cf. Deut. 25:17–19), the Midianites also posed a serious threat to Israel. Whereas Amalek endangered Israel’s very existence, Midian profoundly threatened Israel’s spiritual and moral integrity as the people of God. With the help of the devious pagan prophet Balaam, the Midianites devised a plan to lead Israel into pagan worship. This involved ritual sex, feasting before their Baal, and bowing and sacrificing to him (Num. 25:1–2; 31:16). When he couldn’t bring a curse down on Israel (Num. 22–24), he sought another way.
This is why Moses gives the command, “Now kill all the boys. And kill every woman who has slept with a man, but save for yourselves every girl who has never slept with a man” (Num. 31:17–18 NIV). This command must be understood in the context of Numbers 25. At Peor, the Midianite women deliberately seduced the Israelite men into orgiastic adultery as well as Baal worship.
The death sentence for all males is unusual. However, males were the potential enemy army to rise up against Israel. (Keep in mind that the Israelite males who participated in the seduction were also put to death.) Midian’s brazen, evil intent to lead Israel astray called for a severe judgment. The intent of Moses’s command was to undermine any future Midianite threat to Israel’s identity and integrity.
What about the taking of young virgins? Some critics have crassly suggested that Israelite men were free simply to grab and rape young virgins. Not so. They were saved precisely because they hadn’t degraded themselves by seducing Israelite men. As a backdrop, have a look again at Deuteronomy 21:10–14. There, a Gentile female POW couldn’t be used as a sex object. An Israelite male had to carefully follow proper procedures before she could be taken as a wife. In light of the highly sensitive nature of sexual purity in Israel and for Israel’s soldiers, specific protocols had to be followed. Rape was most certainly excluded as an extracurricular activity in warfare.