philihpAboutPGPLightning

Java for-each iterating with a Scanner

Philihp Busby,0 min read

Usually you want to do something like this, with String.split(...) 

for(String unit : units.split(",")) { System.out.println("unit: "+unit); }

But if for some reason you need the functionality that Scanner  affords, and although it's probably not very readable, you can use an anonymous class to do it like this

for (String unit : new Iterable() { public Iterator iterator() { Scanner scanner = new Scanner(units); scanner.useDelimiter(","); return scanner; } }) { System.out.println("unit: " + unit); }

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.