Upload
jetbrains-russia
View
52
Download
2
Embed Size (px)
Citation preview
Разработка IntelliJ IDEA—впечатления новичка
Тагир Валеев
Java 8 Stream API—• StreamEx library: enhancing Java 8 Streams
https://github.com/amaembo/streamex
• StackOverflow: java-stream Gold badge (один из трёх!)http://stackoverflow.com/help/badges/5670/java-stream
• Патчи в OpenJDK Stream API (~15 штук)http://hg.openjdk.java.net/jdk9/dev/jdk/log?rev=valeev&revcount=2000
Статический анализ кода—• FindBugs contributor
https://github.com/findbugsproject/findbugs• Поиск методов без побочных эффектов
• Анализ целочисленных диапазонов
• Десятки других детекторов
• HuntBugs projecthttps://github.com/amaembo/huntbugs
• Полностью новый проект, > 200 предупреждений (~50% функциональности FindBugs).
Что мне удалось сделать?—• Оптимизация цепочек вызовов Stream API
• Использование новых методов для работы с коллекциями
• Превращение циклов for в вызовы Stream API
• Много мелочей (всего ~50 закрытых задач)
Оптимизации вызовов Stream API—
long count = collection.stream().flatMap(List::stream).count();
long count = collection.stream().mapToLong(List::size).sum();
Упрощение вызовов Stream API—
int totalLength = strings.stream().collect(
Collectors.mapping(String::trim, Collectors.summingInt(String::length)));
int totalLength = strings.stream().map(String::trim).collect(
Collectors.summingInt(String::length));
Упрощение вызовов Stream API—
int totalLength = strings.stream().collect(
Collectors.mapping(String::trim, Collectors.summingInt(String::length)));
int totalLength = strings.stream().map(String::trim).collect(
Collectors.summingInt(String::length));
int totalLength = strings.stream().map(String::trim).mapToInt(String::length).sum();
Упрощение вызовов Stream API—
int totalLength = strings.stream().collect(
Collectors.mapping(String::trim, Collectors.summingInt(String::length)));
int totalLength = strings.stream().map(String::trim).collect(
Collectors.summingInt(String::length));
int totalLength = strings.stream().map(String::trim).mapToInt(String::length).sum();
int totalLength = strings.stream().mapToInt((s) -> s.trim().length()).sum();
(2017.1)
Использование новых методов для коллекций—Iterator<String> it =
collection.iterator();
while(it.hasNext()) {
if(it.next().contains("bad")) {
it.remove();
}
}
collection.removeIf(
s -> s.contains("bad"));
List<String> list = map.get(key);
if(list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(value);
List<String> list =
map.computeIfAbsent(key,
k -> new ArrayList<>());
list.add(value);
Преобразование циклов в Stream API—
long countNonEmpty(List<List<String>> list) {
long count = 0;
for(List<String> subList : list) {
if(subList != null) {
for(String item : subList) {
if(item != null &&
!item.isEmpty()) {
count++;
}
}
}
}
return count;
}
long count = list.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(item -> item != null &&
!item.isEmpty())
.count();
return count;
List<String> list = this.set.stream().collect(Collectors.toList());
List<String> list = this.set.stream().collect(Collectors.toList());
List<String> list = this.new ArrayList<>(set);
public class CompressedRefs {
...
@NotNull
public Stream<VcsRef> stream() {
return Stream.concat(streamBranches(), streamTags());
}
@NotNull
public Collection<VcsRef> getRefs() {
return new AbstractCollection<VcsRef>() {
private final Supplier<Collection<VcsRef>> myLoadedRefs =
Suppliers.memoize(() -> CompressedRefs.this.stream()
.collect(Collectors.toList()));
...
}
...
}
...
}
PsiMethod m = methodCall.resolveMethod();
if(m != null && m.getName().equals("toList") &&
m.getParameterList().getParametersCount() == 0) {
PsiClass c = m.getContainingClass();
if(c.getQualifiedName().equals("java.util.stream.Collectors")) {
// Наш коллектор!
}
}
list.stream().collect(Collectors.toList());
list.stream().collect(java.util.stream.Collectors.toList());
import static java.util.stream.Collectors.toList;
list.stream().collect(toList());
PsiMethod m = methodCall.resolveMethod();
if(m != null && m.getName().equals("toList") &&
m.getParameterList().getParametersCount() == 0) {
PsiClass c = m.getContainingClass();
if(c.getQualifiedName().equals("java.util.stream.Collectors")) {
// Наш коллектор!
}
}
import com.example.Collectors;
list.stream().collect(Collectors.toList());
import static com.example.MyCollectors.toList;
list.stream().collect(toList());
PsiMethod m = methodCall.resolveMethod();
if(m != null && m.getName().equals("toList") &&
m.getParameterList().getParametersCount() == 0) {
PsiClass c = m.getContainingClass();
if(c.getQualifiedName().equals("java.util.stream.Collectors")) {
// Наш коллектор!
}
}
set.stream().collect(Collectors.toList());
new ArrayList<>(set);
PsiExpression replacement = factory
.createExpressionFromText("new java.util.ArrayList<>(" +
collectionExpression.getText() + ")", collectCall);
PsiElement result = collectCall.replace(replacement);
JavaCodeStyleManager.getInstance(project).shortenClassReferences(result);
public Iterator<Object> copyAndGetIterator(List<String> input) {
return input.stream().collect(Collectors.<Object>toList()).iterator();
}
public Iterator<Object> copyAndGetIterator(List<String> input) {
return input.stream().collect(Collectors.<Object>toList()).iterator();
}
public Iterator<Object> copyAndGetIterator(List<String> input) {
return new ArrayList<>(input).iterator();
}
public Iterator<Object> copyAndGetIterator(List<String> input) {
return new ArrayList<Object>(input).iterator();
}
if (PsiDiamondTypeUtil.canCollapseToDiamond(newExpr, newExpr, null)) {
PsiDiamondTypeUtil.replaceExplicitWithDiamond(classRef.getParameterList());
}
set.stream().collect(Collectors.toSet());
new HashSet<>(set);
set.stream().collect(Collectors.toCollection(LinkedHashSet::new));
new LinkedHashSet<>(set);
Спасибо за внимание
—
jetbrains.com