Random Java snippets Flashcards
trim the extension from a filename
str.substring(0, lastIndexOf(‘.’)
capitalize first letter of a String
str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase()
Copies all of the elements from one list into another
Collections.copy
(List super T> dest, List extends T> src)
Returns true if the two specified collections have no elements in common
Collections.disjoint
(Collection> c1, Collection> c2)
Return the name of the dish - the dish may be null.
public Optional getDishName(Dish dish)
return Optional.ofNullable(dish).map(Dish::getName)
Print out name of a vegetarian dish, if any.
public void printVeggieDish(List menu)
Optional.ofNullable(menu) .orElse(Collections.emptyList()) .stream() .filter(Dish::isVegetarian) .findAny() .ifPresent(System.out::println);
Streams: Transaction: Trader: Comparator—
Find all traders from Cambridge and sort them by name alphabetically.
public List cambridgeTraders()
return transactions.stream()
.map(Transaction::getTrader)
.distinct()
.filter(trader -> trader.getCity().equals(“Cambridge”)
.sorted(Comparator.comparing(trader.getName())
.collect(Collectors.toList());
Streams: Transaction: Trader: Collector
Return a single string of all traders’ names sorted alphbetically.
public String traderNames()
return transactions.stream() .map(Transaction::getTrader) .map(Trader::getName) .distinct() .sorted() .collect(Collectors.joining());
Notes:
- flatMap not needed, since one item in in, one item out: flatMap is needed when one item in, list of items based on that one item comes out
- distinct better suited after getTrader, but wanted to illustrate the point 1 above
Stream: Transaction: Trader: terminal operation
Are there any traders based in Milan?
public boolean isMilanBased()
return transactions.stream()
.map(Transaction::getTrader)
.anyMatch(trader -> trader.getCity().equals(“Milan”);
Stream: Transaction: Comparator
What’s the highest value of all the transactions:
public Optional highestValueTrade()
return transactions.stream()
.map(Transaction::getValue)
.max(Comparator.naturalOrder());
Note:
- max(Comparator.comparing(Transaction::getValue) returns a transaction, so based on the signature we need to pull value first
- the terminal operation ‘max’ returns an Optional
Stream: Transaction: Comparator
Find the transaction with the smallest value.
public Optional smallestTransaction()
return transaction.stream()
.min(Comparator.comparing(Transaction::getValue);
Stream: Transaction: sorted-Comparator
Find all transactions in the year 2011 and sort them by value (small to large).
public List transactions2011()
return transactions.stream()
.filter(transaction -> transaction.getYear().equals(2011)
.sorted(Comparator.comparingInt(Transaction::getValue)
.collect(Collectors.toList());
what is result of this stream?
result = files.stream
.filter(file ->file.contains(“.doc”);
nothing, because the stream doesn’t evaluate (no terminating operation)
difference between
list. stream().forEach(Consumer action);
list. forEach(Consumer action);
nothing - so the second way is better - if you only need forEach, then don’t need to stream a list;
(basically if the stream has only a terminating operation, then you can prob do it directly without stream)
For the following code:
students.stream().filter(Student::isFemale).collect(Collectors.toList());
what kind of list is created?
We cannot assume any particular List implementation with this method.
If I wanted to ensure my created list was a
-LinkedList
-ArrayList
how would I change the following code?
students.stream().filter(Student::isFemale).collect(Collectors.toList());
.collect(toCollection(LinkedList::new)
or
.collect(toCollection(ArrayList::new)
run-time safety with enum: what line of code protects from NullPointerException?
if (testPz.getStatus().equals(Pizza.PizzaStatus.DELIVERED) {..}
if (test.Pz.getStatus() == Pizza.PizzaStatus.DELIVERED) {..}
when we use ==, either value can be null and we won’t get an NPE.
conversely, if we use the equals method, we will get an NPE.
- what does this code return?
BigDecimal lowPrice = lookUpSalePrice(productId);
return Optional.ofNullable(lowPrice); - how to return zero if lowPrice is not found?
- it returns an empty Optional if lowPrice is null, otherwise it wraps lowPrice in an Optional
- return Optional.ofNullable(lowPrice).orElse(new BigDecimal(0));
what are methods of BigDecimal?
BigDecimal b1 = new BigDecimal(2); BigDecimal b2 = new BigDecimal(10);
b1. add(b2);
b1. subtract(b2);
b1. multiply(b2);
b1. divide(b2);
b1. negate();
b1. pow(5); //raise to the 5th power. Power must be int!
b1. sqrt()
BigDecimal constants
BigDecimal.ZERO
BigDecimal.ONE
BigDecimal.TEN
String t = “trailMix”;
- t.substring(t.indexOf(“l”))
- t.substring(t.indexOf(“r”), t.indexOf(“M”)
- how to print out “trai”?
- how to get the substring coming after first occurance of “a”?
- lMix (inclusive startIndex)
- rail (exclusive endIndex)
- t.substring(0, t.indexOf(“l”)
- t.substring(t.indexOf(“a”) + 1)
lazy evaluation on stream
a stream doesn’t process the element until it reaches a terminal operation; then it evaluates the .process in order ~1 at a time*
*Note: stateful intermediate operation - i.e. like .sort() or .filter() - is processed “not one at a time” (?)
- Optional.ofNullable - after the .orElse() / orElseGet() we get the value, before we get the Optional
- Optional.of().stream - can change a String into a stream, also can do this with Optional.ofNullable
- Optionals don’t need .stream()
- Lists need .stream()
- map, filter, sort, etc are skipped if the Optional or the List is empty
- Optional.empty()
- listName.isEmpty()
- Optional.ofNullable - after the .orElse() / orElseGet() we get the value, before we get the Optional
- Optional.of().stream - can change a String into a stream, also can do this with Optional.ofNullable
- Optionals don’t need .stream()
- Lists need .stream()