Random Java snippets Flashcards

1
Q

trim the extension from a filename

A

str.substring(0, lastIndexOf(‘.’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

capitalize first letter of a String

A

str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Copies all of the elements from one list into another

A

Collections.copy

(List super T> dest, List extends T> src)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Returns true if the two specified collections have no elements in common

A

Collections.disjoint

(Collection> c1, Collection> c2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Return the name of the dish - the dish may be null.

public Optional getDishName(Dish dish)

A

return Optional.ofNullable(dish).map(Dish::getName)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Print out name of a vegetarian dish, if any.

public void printVeggieDish(List menu)

A
Optional.ofNullable(menu)
     .orElse(Collections.emptyList())
     .stream()
     .filter(Dish::isVegetarian)
     .findAny()
     .ifPresent(System.out::println);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Streams: Transaction: Trader: Comparator—
Find all traders from Cambridge and sort them by name alphabetically.
public List cambridgeTraders()

A

return transactions.stream()
.map(Transaction::getTrader)
.distinct()
.filter(trader -> trader.getCity().equals(“Cambridge”)
.sorted(Comparator.comparing(trader.getName())
.collect(Collectors.toList());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Streams: Transaction: Trader: Collector
Return a single string of all traders’ names sorted alphbetically.
public String traderNames()

A
return transactions.stream()
     .map(Transaction::getTrader)
     .map(Trader::getName)
     .distinct()
     .sorted()
     .collect(Collectors.joining());

Notes:

  1. 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
  2. distinct better suited after getTrader, but wanted to illustrate the point 1 above
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Stream: Transaction: Trader: terminal operation
Are there any traders based in Milan?
public boolean isMilanBased()

A

return transactions.stream()
.map(Transaction::getTrader)
.anyMatch(trader -> trader.getCity().equals(“Milan”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Stream: Transaction: Comparator
What’s the highest value of all the transactions:
public Optional highestValueTrade()

A

return transactions.stream()
.map(Transaction::getValue)
.max(Comparator.naturalOrder());

Note:

  1. max(Comparator.comparing(Transaction::getValue) returns a transaction, so based on the signature we need to pull value first
  2. the terminal operation ‘max’ returns an Optional
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Stream: Transaction: Comparator
Find the transaction with the smallest value.
public Optional smallestTransaction()

A

return transaction.stream()

.min(Comparator.comparing(Transaction::getValue);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Stream: Transaction: sorted-Comparator
Find all transactions in the year 2011 and sort them by value (small to large).
public List transactions2011()

A

return transactions.stream()
.filter(transaction -> transaction.getYear().equals(2011)
.sorted(Comparator.comparingInt(Transaction::getValue)
.collect(Collectors.toList());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what is result of this stream?
result = files.stream
.filter(file ->file.contains(“.doc”);

A

nothing, because the stream doesn’t evaluate (no terminating operation)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

difference between

list. stream().forEach(Consumer action);
list. forEach(Consumer action);

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

For the following code:
students.stream().filter(Student::isFemale).collect(Collectors.toList());

what kind of list is created?

A

We cannot assume any particular List implementation with this method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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());

A

.collect(toCollection(LinkedList::new)
or
.collect(toCollection(ArrayList::new)

17
Q

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) {..}

A

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.

18
Q
  1. what does this code return?
    BigDecimal lowPrice = lookUpSalePrice(productId);
    return Optional.ofNullable(lowPrice);
  2. how to return zero if lowPrice is not found?
A
  1. it returns an empty Optional if lowPrice is null, otherwise it wraps lowPrice in an Optional
  2. return Optional.ofNullable(lowPrice).orElse(new BigDecimal(0));
19
Q

what are methods of BigDecimal?

A
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()

20
Q

BigDecimal constants

A

BigDecimal.ZERO
BigDecimal.ONE
BigDecimal.TEN

21
Q

String t = “trailMix”;

  1. t.substring(t.indexOf(“l”))
  2. t.substring(t.indexOf(“r”), t.indexOf(“M”)
  3. how to print out “trai”?
  4. how to get the substring coming after first occurance of “a”?
A
  1. lMix (inclusive startIndex)
  2. rail (exclusive endIndex)
  3. t.substring(0, t.indexOf(“l”)
  4. t.substring(t.indexOf(“a”) + 1)
22
Q

lazy evaluation on stream

A

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” (?)

23
Q
  1. Optional.ofNullable - after the .orElse() / orElseGet() we get the value, before we get the Optional
  2. Optional.of().stream - can change a String into a stream, also can do this with Optional.ofNullable
A
  • 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()
24
Q
  1. Optional.ofNullable - after the .orElse() / orElseGet() we get the value, before we get the Optional
  2. Optional.of().stream - can change a String into a stream, also can do this with Optional.ofNullable
A
  • Optionals don’t need .stream()

- Lists need .stream()

25
Q

deadlock

A

while sysnchronization can achieve thread safety, it can lead to unwanted effects on a system such as slowdowns and a state known as deadlock.

deadlock - two or more threads have some form of codependency in their (ie their stack’s) variables. Neither thread can proceed until the other finishes due to locks on those variables.

while this situation can cause a deadlock, since threads run unpredictably, it won’t always cause a deadloc –> hard to debug.

this happens when:
- multiple threads try to lock multiple objects in a different order –> usually because multiple synchronized methods across instances call each other.

26
Q
1. synchronized method
vs 
2. atomic variable
vs 
3. immutable object
A

1.

  1. atomic object type (used on a variable in a class)
    - safely share changing state across threads
  2. immutable object
    - share unchanging state between threads
27
Q

threads run code at the same time as our main program

A
  • each thread has its own stack that is independent of the main() execution stack
  • object references on each stack point to values stored on the heap
  • all object instances are stored in the heap, which is used by the entire application
  • multiple threads can reference the same object in the heap, so any change in one thread makes to a shared object in the heap impacts other threads (so we have to lock partially/fully the object for the currentThread, and have the other Threads wait)
28
Q

threads run code at the same time as our main program

A
  • each thread has its own stack that is independent of the main() execution stack
  • object references on each stack point to values stored on the heap
  • all object instances are stored in the heap, which is used by the entire application
  • multiple threads can reference the same object in the heap, so any change in one thread makes to a shared object in the heap impacts other threads (so JVM locks partially/fully the object for the currentThread, and have the other Threads wait “BLOCKED”, after unlocked JVM marks all BLOCKED as RUNNABLE)
29
Q

conference audience microphones system to illustrate synchronized methods

A
class MicrophoneService {
   List microphoneList;
   synchrozied turnOnMicStream(micId) {}
   synchronized useMic(micId)
   requestMic()

}

30
Q

setup a Thread

A
public static void main(String[] args) {
    GiftCard giftCard = new GiftCard(25);
    // thread takes in a Runnable
    Thread depositThread1 = new Thread(new GiftCardDepositer(giftCard, 5);
    Thread depositThread2 = new Thread(new GiftCardDepositer(giftCard, 10);
31
Q

setup a Thread

A
public static void main(String[] args) {
    GiftCard giftCard = new GiftCard(25);
    // thread takes in a Runnable
    Thread depositThread1 = new Thread(new GiftCardDepositer(giftCard, 5);
    Thread depositThread2 = new Thread(new GiftCardDepositer(giftCard, 10);
giftCard.printBalance();
depositThread1.start();    //need to start the Thread!
depositThread2.start(); }

^^since both threads will access a method within GiftCardDepositer which adds funds to the giftCard, that method must be synchronized! so if thread1 accesses it first, thread2 is BLOCKED from calling addFunds() until JVM marks it as RUNNABLE again.

32
Q

“Could you still use non-synchronized methods of that class or are those locked out as well?”

A

Another thread can invoke non-synchronized methods even if the lock has been retrieved by another thread calling a synchronized method. Any thread can call an unsynchronized method at any time.

33
Q

to make a class immutable - 3 things

A
  1. make the class members private final
  2. use defensive copying on any members that use mutable objects
  3. remove any setters
34
Q

how to synchronize objects?

A

use Atomic object types and their corresponding atomic methods

35
Q

atomic object types

A

AtomicInteger
AtomicLong
AtomicBoolean
AtomicReference - wraps an object reference to make the reference atomic

36
Q

common functions of atomic objects

A

get()
set(value)
compareAndSet(expect, update)

37
Q

AtomicInteger functions

A

addAndGet(int)

getAndSet(int)