0% found this document useful (0 votes)
4 views

strings-io-and-other-bits-and-pieces-slides

The document provides various examples of Java programming techniques, including string manipulation, stream operations, and the use of collections. It covers features from different Java versions, such as StringJoiner in JDK 8 and try-with-resources in JDK 7. Additionally, it discusses the use of comparators and maps, showcasing how to manipulate and access data effectively.

Uploaded by

Chinni Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

strings-io-and-other-bits-and-pieces-slides

The document provides various examples of Java programming techniques, including string manipulation, stream operations, and the use of collections. It covers features from different Java versions, such as StringJoiner in JDK 8 and try-with-resources in JDK 7. Additionally, it discusses the use of comparators and maps, showcasing how to manipulate and access data effectively.

Uploaded by

Chinni Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93








String s = "Hello world!";


String s = "Hello world!";


IntStream stream = s.chars(); // creates a Stream on
// the letters of s

String s = "Hello world!";


IntStream stream = s.chars(); // creates a Stream on
// the letters of s
stream.mapToObj(letter -> (char)letter)
.map(Character::toUpperCase)
.forEach(System.out::print);

> HELLO WORLD!


String s1 = "Hello";
String s2 = "world";

String s = s1 + " " + s2; // it works!


String s1 = "Hello";
String s2 = "world";

String s = s1 + " " + s2; // it works!


StringBuffer sb1 = new StringBuffer();


sb1.append("Hello");

StringBuffer sb1 = new StringBuffer();


sb1.append("Hello");
sb1.append(" ").append("world"); // can be chained

StringBuffer sb1 = new StringBuffer();


sb1.append("Hello");
sb1.append(" ").append("world"); // can be chained
String s = sb1.toString();

StringBuffer sb1 = new StringBuffer();


sb1.append("Hello");
sb1.append(" ").append("world"); // can be chained
String s = sb1.toString();


// The JDK 5 way


StringBuilder sb1 = new StringBuilder();
sb1.append("Hello");
sb1.append(" ").append("world"); // can be chained
String s = sb1.toString();


// The JDK 5 way


StringBuilder sb1 = new StringBuilder();
sb1.append("Hello");
sb1.append(" ").append("world"); // can be chained
String s = sb1.toString();


// The JDK 8 way


StringJoiner sj = new StringJoiner(", ");
sj.add("one").add("two").add("three");

// The JDK 8 way


StringJoiner sj = new StringJoiner(", ");
sj.add("one").add("two").add("three");
String s = sj.toString();
System.out.println(s);

> one, two, three


// The JDK 8 way


StringJoiner sj = new StringJoiner(", ", "{", "}");
// we leave the joiner empty
String s = sj.toString();
System.out.println(s);

// The JDK 8 way


StringJoiner sj = new StringJoiner(", ", "{", "}");
// we leave the joiner empty
String s = sj.toString();
System.out.println(s);

> {}

// The JDK 8 way


StringJoiner sj = new StringJoiner(", ", "{", "}");
sj.add("one");
String s = sj.toString();
System.out.println(s);

> {one}

// The JDK 8 way


StringJoiner sj = new StringJoiner(", ", "{", "}");
sj.add("one").add("two").add("three");
String s = sj.toString();
System.out.println(s);

> {one, two, three}


// From the String class, with a vararg


String s = String.join(", ", "one", "two", "three");
System.out.println(s);

> one, two, three


// From the String class, with an Iterable


String [] tab = {"one", "two", "three"};
String s = String.join(", ", tab);
System.out.println(s);

> one, two, three


// Java 7 : try with resources


try (BufferedReader reader =
new BufferedReader(
new FileReader(
new File("d:/tmp/debug.log")));) {

Stream<String> stream = reader.lines();


stream.filter(line -> line.contains("ERROR"))
.findFirst()
.ifPresent(System.out::println);

} catch (IOException ioe) {


// handle the exception
}

// Java 7 : try with resources and use of Paths


Path path = Paths.get("d:", "tmp", "debug.log");
try (Stream<String> stream = Files.lines(path)) {

stream.filter(line -> line.contains("ERROR"))


.findFirst()
.ifPresent(System.out::println);

} catch (IOException ioe) {


// handle the exception
}

// Java 7 : try with resources and use of Paths


Path path = Paths.get("d:", "tmp", "debug.log");
try (Stream<String> stream = Files.lines(path)) {

stream.filter(line -> line.contains("ERROR"))


.findFirst()
.ifPresent(System.out::println);

} catch (IOException ioe) {


// handle the exception
}


// Java 7 : try with resources and use of Paths


Path path = Paths.get("c:", "windows");
try (Stream<Path> stream = Files.list(path)) {

stream.filter(path -> path.toFile().isDirectory())


.forEach(System.out::println);

} catch (IOException ioe) {


// handle the exception
}

// Java 7 : try with resources and use of Paths


Path path = Paths.get("c:", "windows");
try (Stream<Path> stream = Files.list(path)) {

stream.filter(path -> path.toFile().isDirectory())


.forEach(System.out::println);

} catch (IOException ioe) {


// handle the exception
}


// Java 7 : try with resources and use of Paths


Path path = Paths.get("c:", "windows");
try (Stream<Path> stream = Files.walk(path)) {

stream.filter(path -> path.toFile().isDirectory())


.forEach(System.out::println);

} catch (IOException ioe) {


// handle the exception
}

// Java 7 : try with resources and use of Paths


Path path = Paths.get("c:", "windows");
try (Stream<Path> stream = Files.walk(path, 2)) {

stream.filter(path -> path.toFile().isDirectory())


.forEach(System.out::println);

} catch (IOException ioe) {


// handle the exception
}



// Unfortunately not for arrays


List<String> strings =
Arrays.asList("one", "two", "three");

strings.forEach(System.out::println);

// removes an element on a predicate
Collection<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


Collection<String> list = new ArrayList<>(strings);

// returns true if the list has been modified


boolean b = list.removeIf(s -> s.length() > 4);

System.out.println(
list.stream().collect(Collectors.joining(", ")));

// removes an element on a predicate
Collection<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


Collection<String> list = new ArrayList<>(strings);

// returns true if the list has been modified


boolean b = list.removeIf(s -> s.length() > 4);

System.out.println(
list.stream().collect(Collectors.joining(", ")));

> one, two, four



// removes an element on a predicate
List<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


List<String> list = new ArrayList<>(strings);

// doesnt return anything


list.replaceAll(String::toUpperCase);

System.out.println(
list.stream().collect(Collectors.joining(", ")));

// removes an element on a predicate
List<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


List<String> list = new ArrayList<>(strings);

// doesnt return anything


list.replaceAll(String::toUpperCase);

System.out.println(
list.stream().collect(Collectors.joining(", ")));

> ONE, TWO, THREE, FOUR



// removes an element on a predicate
List<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


List<String> list = new ArrayList<>(strings);

// doesnt return anything


list.sort(Comparator.naturalOrder());

System.out.println(
list.stream().collect(Collectors.joining(", ")));

// removes an element on a predicate
List<String> strings =
Arrays.asList("one", "two", "three", "four");

// will not work if list is unmodifiable


List<String> list = new ArrayList<>(strings);

// doesnt return anything


list.sort(Comparator.naturalOrder());

System.out.println(
list.stream().collect(Collectors.joining(", ")));

> four, one, three, two



// comparison using the last name
Comparator<Person> compareLastName =
new Comparator<Person>() {

@Override
public int compare(Person p1, Person p2) {
return p1.getLastName().compareTo(p2.getLastName());
}
};

// comparison using the last name
Comparator<Person> compareLastName =
new Comparator<Person>() {

@Override
public int compare(Person p1, Person p2) {
return p1.getLastName().compareTo(p2.getLastName());
}
};



// comparison using the last name then the first name
Comparator<Person> compareLastNameThenFirstName =
new Comparator<Person>() {

@Override
public int compare(Person p1, Person p2) {
int lastNameComparison =
p1.getLastName().compareTo(p2.getLastName());
return lastNameComparison == 0 ?
p2.getFirstName().compareTo(p2.getFirstName());
lastNameComparison;
}
};



// comparison using the last name
Comparator<Person> compareLastName =
Comparator.comparing(Person::getLastName);

// comparison using the last name
Comparator<Person> compareLastName =
Comparator.comparing(Person::getLastName);



// comparison using the last name and then the first name
Comparator<Person> compareLastNameThenFirstName =
Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName);



// reverses a comparator
Comparator<Person> comp = ...;

Comparator<Person> reversedComp = comp.reversed();



// compares comparable objects
Comparator<String> c = Comparator.naturalOrder();

// compares comparable objects
Comparator<String> c = Comparator.naturalOrder();

// compares comparable objects in the reverse order


Comparator<String> c = Comparator.reversedOrder();

// considers null values lesser than non-null values
Comparator<String> c =
Comparator.nullsFirst(Comparator.naturalOrder());

// considers null values lesser than non-null values
Comparator<String> c =
Comparator.nullsFirst(Comparator.naturalOrder());

// considers null values greater than non-null values


Comparator<String> c =
Comparator.nullsLast(Comparator.naturalOrder());



long max = Long.max(1L, 2L);

BinaryOperator<Long> sum = (l1, l2) -> l1 + l2;


= (l1, l2) -> Long.sum(l1, l2);
= Long::sum;

// JDK 7
long l = 3141592653589793238L;
int hash = new Long(l).hashCode(); // -1985256439

// JDK 7
long l = 3141592653589793238L;
int hash = new Long(l).hashCode(); // -1985256439



// JDK 7
long l = 3141592653589793238L;
int hash = new Long(l).hashCode(); // -1985256439

// JDK 8
long l = 3141592653589793238L;
int hash = Long.hashCode(l); // - 1985256439



Map<String, Person> map = ...;
map.forEach((key, person) ->
System.out.println(key + " " + person);



Map<String, Person> map = ...;

Person p = map.get(key); // p can be null!



Map<String, Person> map = ...;

Person defaultPerson = Person.DEFAULT_PERSON;


Person p = map.getOrDefault(key, defaultPerson); // JDK 8



Map<String, Person> map = ...;

map.put(key, person); // will erase an existing person



Map<String, Person> map = ...;

map.put(key, person);
map.putIfAbsent(key, person); // JDK8



Map<String, Person> map = ...;

map.replace(key, person);



Map<String, Person> map = ...;

map.replace(key, person);
map.replace(key, oldPerson, newPerson);



Map<String, Person> map = ...;

map.replace(key, person);
map.replace(key, oldPerson, newPerson);

map.replaceAll((key, oldPerson) -> newPerson);



Map<String, Person> map = ...;
map.remove(key);

Map<String, Person> map = ...;
map.remove(key); // JDK 7
map.remove(key, person); // JDK 8



Map<String, Person> map = ...;

map.compute(key, person, (key, oldPerson) -> newPerson);



Map<String, Person> map = ...;

map.computeIfPresent(key, person, (key, oldPerson) -> newPerson);



Map<String, Person> map = ...;

map.computeIfAbsent(key, key -> newPerson);



Map<String, Person> map = ...;

map.computeIfAbsent(key, key -> newPerson);

Map<String, Map<Integer, Person>> bimap = ...;


Person p = ...;

bimap.computeIfAbsent(key1, key -> new HashMap<>()).put(key2, p);



Map<String, Person> map = ...;

map.merge(key, person, (key, person) -> newPerson);



@TestCases({
@TestCase(param=1, expected=false),
@TestCase(param=2, expected=true)
})
public boolean even(int param) {
return param % 2 == 0;
}


@TestCases({
@TestCase(param=1, expected=false),
@TestCase(param=2, expected=true)
})
public boolean even(int param) {
return param % 2 == 0;
}



@TestCase(param=1, expected=false)
@TestCase(param=2, expected=true)
public boolean even(int param) {
return param % 2 == 0;
}


@TestCase(param=1, expected=false)
@TestCase(param=2, expected=true)
public boolean even(int param) {
return param % 2 == 0;
}





@interface TestCase {
int param();
boolean expected();
}

@interface TestCases {
TestCase[] value();
}

@Repeatable(TestCases.class)
@interface TestCase {
int param();
boolean expected();
}

@interface TestCases {
TestCase[] value();
}

private @NonNull List<Person> persons = ... ;


private @NonNull List<Person> persons = ... ;

private @NonNull List<@NonNull Person> persons = ... ;


You might also like