Skip to content

Instantly share code, notes, and snippets.

@sagarr
Created January 13, 2018 17:36
Show Gist options
  • Save sagarr/783a11a006285b72cc1e7d20cac9714a to your computer and use it in GitHub Desktop.
Save sagarr/783a11a006285b72cc1e7d20cac9714a to your computer and use it in GitHub Desktop.
package com.rohankar.tourist;
import io.vavr.Tuple3;
import io.vavr.collection.Stream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.toList;
/**
* Java 8 (using Vavr) version of original Tourist example written in Kotlin.
* See: http://blog.dhananjaynene.com/2018/01/analysing-tourism-data-with-kotlin
*
* @author Sagar Rohankar
*/
public class Tourist {
public static void main(String[] args) throws IOException {
Stream<String> strings = Stream.ofAll(Files.readAllLines(new File("tourists-to-india.csv").toPath()));
strings
.drop(1) // csv header
.dropRight(1) // total row
.map(row -> row.split(","))
.map(arr -> {
List<Integer> visitors = Arrays.stream(Arrays.copyOfRange(arr, 2, arr.length))
.mapToInt(Integer::parseInt)
.boxed()
.collect(toList());
return new Tuple3<>(arr[0], arr[1], visitors); // <Country, Continent, Visitors>
})
.groupBy(countryContinentVisitors -> countryContinentVisitors._2) // by Continent
.mapValues(tuple -> {
int tourist2001 = tuple.map(Tuple3::_3)
.map(l -> l.get(0))
.sum()
.intValue();
int tourist2015 = tuple.map(Tuple3::_3)
.map(l -> l.get(14))
.sum()
.intValue();
double pctGrowth = (tourist2015 - tourist2001) * 100 / tourist2001;
String maxCountry = tuple
.sortBy(t -> t._3()
.stream()
.mapToInt(Integer::intValue)
.sum())
.last()
._1;
return new Tuple3<>(tourist2015, pctGrowth, maxCountry);
})
.map(tuple -> tuple._2) // skip tuple._1 which is continent
.sorted(naturalOrder())
.forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment