Skip to content

Instantly share code, notes, and snippets.

@iamlow
Last active March 21, 2017 08:27
Show Gist options
  • Select an option

  • Save iamlow/2b877d3a742c92b26a53cf20e2d8ea41 to your computer and use it in GitHub Desktop.

Select an option

Save iamlow/2b877d3a742c92b26a53cf20e2d8ea41 to your computer and use it in GitHub Desktop.
StreamAPI Example
public class StreamAPI {
public static void main(String ...args) {
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario","Milan");
Trader alan = new Trader("Alan","Cambridge");
Trader brian = new Trader("Brian","Cambridge");
List<Transaction> transactions = Arrays.asList(
new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000),
new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710),
new Transaction(mario, 2012, 700),
new Transaction(alan, 2012, 950)
);
// Query 1: Find all transactions from year 2011 and sort them by value (small to high).
transactions.stream().filter(t -> t.getYear() == 2011).sorted(comparing(Transaction::getValue)).forEach(System.out::println);
// Query 2: What are all the unique cities where the traders work?
transactions.stream().map(t -> t.getTrader().getCity()).distinct().forEach(System.out::println);
// Query 3: Find all traders from Cambridge and sort them by name.
transactions.stream().map(Transaction::getTrader).filter(t -> t.getCity().equals("Cambridge")).distinct().sorted(comparing(Trader::getName)).forEach(System.out::println);
// Query 4: Return a string of all traders’ names sorted alphabetically.
System.out.println(transactions.stream().map(t -> t.getTrader().getName()).distinct().sorted().reduce("", (n1, n2) -> n1 + n2) + "\n");
// Query 5: Are there any trader based in Milan?
System.out.println(transactions.stream().anyMatch(t -> t.getTrader().getCity().equals("Milan")));
// Query 6: Update all transactions so that the traders from Milan are set to Cambridge.
Optional<Transaction> trans = transactions.stream().filter(t -> t.getTrader().getCity().equals("Cambridge")).findAny();
System.out.println(trans);
// Query 7: What's the highest value in all the transactions?
System.out.println(transactions.stream().map(Transaction::getValue).reduce(Integer::max));
// Query 8: What's the lowest value in all the transactions?
System.out.println(transactions.stream().map(Transaction::getValue).reduce(Integer::min));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment