有没有办法用Java 8 Comparator实现Ordering.lexicographical()?
Comparator.thenCompare似乎在这方面受到限制
你觉得什么更好(当然有论据):
Optional.ofNullable( userName )
.ifPresent( nonNullUserName -> header.setUser( createUser( nonNullUserName ) ) );
Run Code Online (Sandbox Code Playgroud)
要么
header.setUser( userName == null ? createUser( userName ) : null );
Run Code Online (Sandbox Code Playgroud)
该方法createUser创建了xml元素,整个代码安静的意图是根据它的存在将其设置在SOAP请求中userName.
我看到的第一种方法的好处是没有无用的操作,代码做了一件事而不是更多.但是第二种方法可以让你再保存一行代码,从而看起来更简洁.
更新:我想我错过了一个我实际暗示的事情,它引起了一些误解.如果你有一些解释,最好提供更清晰的例子.
我正在寻找一个问题的答案:方法.toArray(IntFunction generator)如何知道新数组的大小.
实际上我知道如何使用这个方法来创建包含所有stream元素的新数组(例如String[]::new, Size -> new String[Size]),但在原始的java代码中我们可以看到IntFunction<A[]>生成器将给定的函数应用于int参数.我的问题是这个函数如何获取流的元素数量.
我已经阅读了这个课程的源代码3个小时,但我找不到答案.
非常感谢!
我想在遍历列表使用lambda时得到索引.
例如:
List<CheckBox> checkBoxes = null;
checkBoxes.forEach(checkBox -> {
if (checkBox.isSelected()) {
sb.append("index"); //I want to get checkbox index here
sb.append(",");
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:这checkBoxes = null;只是一个占位符,但一旦我开始编写代码就会正常使用.
是否有一种更优雅的方式来加入流的元素,用"\n"分隔每个元素,但不以"\n"开头,而不必像下面的例子那样进行子串(1)调用?
List<String> strings = someList;
String rval = strings.stream()
.map(this::someOperation)
.reduce("", (p1, p2) -> p1 + "\n" + p2);
if(rval.length() > 0)
{
// trim off the leading "\n"
rval = rval.substring(1);
}
return rval;
}
Run Code Online (Sandbox Code Playgroud)
当然我可以用内部循环替换它,但这会失去明显的功能可读性
我想从bean列表中的枚举属性列表中计算最高序数枚举值.
例如,我有:
@Data
public class MyBean {
private Priority priority;
}
Run Code Online (Sandbox Code Playgroud)
和
public enum Priority {
URGENT("Urgent"),
HIGH("High"),
MEDIUM("Medium"),
LOW("Low");
@Getter
private final String value;
Priority(String value) {
this.value = value;
}
@Override
public String toString() {
return getValue();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个List的MyBeans,我怎么能找到bean的的最大序号值priority列表中?
例:
{myBean1, myBean2, myBean3, myBean4} where
myBean1.getPriority() = Priority.LOW
myBean2.getPriority() = Priority.URGENT
myBean3.getPriority() = Priority.HIGH
myBean4.getPriority() = null
returns Priority.URGENT
Run Code Online (Sandbox Code Playgroud)
我认为最糟糕的情况是我可以values()在枚举中迭代Collections.min(Arrays.asList(Priority.values()));并循环遍历每个bean以查看值是否匹配.但这似乎很乏味.
我正在尝试优化以下代码:
private final static class SubarrayProcessorNegativeSumStrategy
implements SubarrayProcessorStrategy {
@Override public Integer apply(Integer[] array) {
final List<Integer> numbers = Arrays.asList(array);
return (int) IntStream.range(0, numbers.size())
.map(index -> findNegativeSums(numbers, index)).sum();
}
private Integer findNegativeSums(final List<Integer> numbers,
final Integer startIndex) {
final Integer numbersSize = numbers.size();
if (startIndex < numbersSize) {
return (int) IntStream.range(startIndex, numbers.size())
.map(newIndex -> numbers.subList(startIndex, newIndex + 1)
.stream().mapToInt(x -> x).sum())
.filter(sum -> sum < 0).count();
} else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我想避免迭代startIndex到newIndex + 1原始List的每个元素 …
我有一个Invoice对象列表,其中包含属性频率和数量(BigDecimal).
1)需要在不考虑精度的情况下,根据频率乘以和改变量.在下面显示的代码中输出但是输出失去了一些精度.金额值应为100.
2)是否可以用Java 8流API替换发票列表中的金额值.尝试使用
invoiceList.forEach(s -> s.getAmount().multiply(new BigDecimal("10")));
Run Code Online (Sandbox Code Playgroud)
但是这不会取代对象中的金额值.在这种情况下无法弄清楚使用replaceAll,尝试下面的代码,但给出编译错误,
newList.replaceAll((v) -> v.getAmount().multiply(frequencyFactor.get(v.getFrequency())));
Run Code Online (Sandbox Code Playgroud)
整个主要课程如下.无法更改任何数据类型或设计.我必须从Web服务处理获取的列表.
public class InvoiceMain {
public static void main(String[] args) {
List<Invoice> invoiceList = Arrays.asList(new Invoice("Quarterly", new BigDecimal(300)), new Invoice("Annually", new BigDecimal(1200)));
Map<String, BigDecimal> frequencyFactor = new HashMap<>();
frequencyFactor.put("Annually", new BigDecimal(1.0 / 12));
frequencyFactor.put("Quarterly", new BigDecimal(1.0 / 3));
for (Invoice invoice : invoiceList) {
invoice.setAmount(invoice.getAmount().multiply(frequencyFactor.get(invoice.getFrequency())));
}
System.out.println(invoiceList);
}
}
class Invoice {
private String frequency;
private BigDecimal amount;
public Invoice(String frequency, BigDecimal amount) {
super();
this.frequency = frequency; …Run Code Online (Sandbox Code Playgroud) 我正从DB中检索大块数据并使用此数据将其写入其他位置.为了避免漫长的处理时间,我正在尝试使用并行流来编写它.
当我将其作为顺序流运行时,它可以完美地运行.但是,如果我将其更改为并行,则行为很奇怪:它会多次打印同一个对象(超过10个).
@PostConstruct
public void retrieveAllTypeRecords() throws SQLException {
logger.info("Retrieve batch of Type records.");
try {
Stream<TypeRecord> typeQueryAsStream = jdbcStream.getTypeQueryAsStream();
typeQueryAsStream.forEach((type) -> {
logger.info("Printing Type with field1: {} and field2: {}.", type.getField1(), type.getField2()); //the same object gets printed here multiple times
//write this object somewhere else
});
logger.info("Completed full retrieval of Type data.");
} catch (Exception e) {
logger.error("error: " + e);
}
}
public Stream<TypeRecord> getTypeQueryAsStream() throws SQLException {
String sql = typeRepository.getQueryAllTypesRecords(); //retrieves SQL query in String format …Run Code Online (Sandbox Code Playgroud) 我正在使用Java 8流。
当我使用分隔符将其添加到地图中时,会得到重复的键异常,但是使用标准的for循环不会引发异常。
// This works
Map<Integer, String> myMap = new HashMap<>();
for (Row row : result.result()) {
myMap.put(row.get(0, Integer.class), null);
}
// This throws exception
myMap = StreamSupport.stream(result.result().spliterator(), true)
.collect(Collectors.toMap(row -> row.get(0, Integer.class), row -> ""));
Run Code Online (Sandbox Code Playgroud)
如果有什么不同,则结果为Cassandra结果集,行为Cassandra行。
java-8 ×10
java ×7
java-stream ×6
lambda ×3
android ×1
arrays ×1
cassandra ×1
comparator ×1
enums ×1
guava ×1
list ×1
optional ×1
performance ×1
reduce ×1