我正在使用新的日期时间API,但在运行时:
public class Test {
public static void main(String[] args){
String dateFormatted = LocalDate.now()
.format(DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(dateFormatted);
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出:
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2543)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDate.format(LocalDate.java:1685)
at Test.main(Test.java:23)
Run Code Online (Sandbox Code Playgroud)
查看LocalDate类的源代码时,我看到:
private int get0(TemporalField field) {
switch ((ChronoField) field) {
case DAY_OF_WEEK: return getDayOfWeek().getValue();
case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + …Run Code Online (Sandbox Code Playgroud) 例如,如果我打算对某些元素进行分区,我可以执行以下操作:
Stream.of("I", "Love", "Stack Overflow")
.collect(Collectors.partitioningBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k + " => " + v));
Run Code Online (Sandbox Code Playgroud)
哪个输出:
false => [I]
true => [Love, Stack Overflow]
Run Code Online (Sandbox Code Playgroud)
但对我partioningBy来说只是一个子问题groupingBy.虽然前者Predicate在后者a中接受as参数Function,但我只看到一个分区作为正常的分组函数.
所以相同的代码完全相同:
Stream.of("I", "Love", "Stack Overflow")
.collect(Collectors.groupingBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k + " => " + v));
Run Code Online (Sandbox Code Playgroud)
这也导致了Map<Boolean, List<String>>.
那么有什么理由我应该用partioningBy而不是groupingBy?谢谢
我看到了Java 7,他们介绍了这个方法Objects.requireNonNull(T obj, String message).
检查指定的对象引用是否为null,
NullPointerException如果是,则抛出自定义对象引用.此方法主要用于在具有多个参数的方法和构造函数中进行参数验证.
在开始重新格式化代码之前,我会在这里要求对使用它进行一些反馈.
public Foo(Bar bar, Baz baz) {
/** Old one
this.bar = bar;
this.baz = baz;
**/
this.bar = Objects.requireNonNull(bar, "bar must not be null");
this.baz = Objects.requireNonNull(baz, "baz must not be null");
}
Run Code Online (Sandbox Code Playgroud)
在构造我的对象时直接使用它是一种更好的做法(我在考虑是否为开发人员创建库或其他东西)?
或者我应该把它留作"经典/旧的"构造函数?
我最近在SO聊天中看到了一个讨论,但没有明确的结论,所以我最后在那里问.
这是出于历史原因还是与其他语言的一致性?在查看compareTo各种语言的签名时,它会返回一个int.
为什么它不返回枚举.例如在C#中我们可以这样做:
enum CompareResult {LessThan, Equals, GreaterThan};
Run Code Online (Sandbox Code Playgroud)
并且:
public CompareResult CompareTo(Employee other) {
if (this.Salary < other.Salary) {
return CompareResult.LessThan;
}
if (this.Salary == other.Salary){
return CompareResult.Equals;
}
return CompareResult.GreaterThan;
}
Run Code Online (Sandbox Code Playgroud)
在Java中,枚举是在这个概念之后引入的(我不记得有关C#)但它可以通过额外的类来解决,例如:
public final class CompareResult {
public static final CompareResult LESS_THAN = new Compare();
public static final CompareResult EQUALS = new Compare();
public static final CompareResult GREATER_THAN = new Compare();
private CompareResult() {}
}
Run Code Online (Sandbox Code Playgroud)
和
interface Comparable<T> {
Compare compareTo(T obj);
}
Run Code Online (Sandbox Code Playgroud)
我问这个是因为我不认为一个int …
这是如何编译而没有错误的?根据我的理解,编译器检查变量的类型(在这种情况下String),然后查看右侧表达式的类型是否对应于变量的类型(或者至少是一个子类型,但让我们坚持使用String上课,因为它是最后的).
public class InitClass {
public static void main(String[] args) {
String str = (str = "hello");
System.out.println(str);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何str = "hello"编译?编译器是否已经知道str应该是类型String?
我创建了一个函数来过滤多个谓词,我为它们执行逻辑AND:
@SafeVarargs
public static <T> Stream<T> filter(Stream<T> source, Predicate<T>... predicates) {
return source.filter(Arrays.stream(predicates).reduce(predicates[0], Predicate::and));
}
Run Code Online (Sandbox Code Playgroud)
致电时:
filter(IntStream.range(0, 10).boxed(), x -> x % 2 != 0, x -> x%3 == 0).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
它工作正常并打印3和9.但是,当我传递一个谓词,如:
filter(IntStream.range(0, 10).boxed(), x -> x % 2 != 0).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
我收到编译错误:
The target type of this expression must be a functional interface
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
对于infos我使用Eclipse Luna版本1.
public class Test {
public static void main(String[] args) {
List<Pair<String, Integer>> list = new ArrayList<>();
list.add(new Pair<>("1", 8));
list.add(new Pair<>("3", 2));
list.add(new Pair<>("2", 15));
list.stream()
.sorted(Comparator.comparingInt(p -> p.v))
.map(p -> p.k)
.forEach(System.out::println);
}
}
class Pair<K, V> {
K k;
V v;
public Pair(K k, V v) {
this.k = k;
this.v = v;
}
}
Run Code Online (Sandbox Code Playgroud)
好的,正如您所了解的那样,此代码是从与最高值关联的最低值打印我的对键,因此我获得了预期的输出:
3 1 2
到现在为止还挺好.现在我想反过来,我想我只需要这样做
list.stream()
.sorted(Comparator.comparingInt(p -> p.v).reversed())
.map(p -> p.k)
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
但我得到一个编译错误:
v cannot be resolved or is not a field …Run Code Online (Sandbox Code Playgroud) 我正在切换到Intellij并尝试做与Eclipse中相同的事情.在Eclipse中,您可以将项目作为依赖项添加到另一个项目中(project properties -> "Java Build Path" -> "Projects" -> Click on my library project).
目前的情况是我正在开发一个库,我可以测试另一个项目中的功能,而无需在每次向库中添加新内容时构建jar文件.
我试图用Intellij实现这一点,但没有成功(项目都是在Intellij中导入的).
我怎样才能做到这一点?
在给定所需布尔值的最大数量的情况下,生成可能的布尔组合的最优雅方法是什么?
例如:
bool(1) -> [false], [true]
bool(2) -> [false, false], [false, true], [true, false], [true, true]
...
Run Code Online (Sandbox Code Playgroud)
这是我目前的实施:
public static List<Boolean[]> bool(int n) {
return IntStream.range(0, (int) Math.pow(2, n))
.mapToObj(i -> StringUtils.leftPad(Integer.toBinaryString(i), n, '0').chars().mapToObj(c -> c != '0').toArray(Boolean[]::new))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
但是我不满意我使用整数,然后映射到二进制,StringUtils.leftPad并map返回一个Boolean[]而不是一个boolean[].
使用Stream API在单线程中有更好的方法吗?
我实际上试图回答这个问题如何跳过从Files.lines获得的Stream <String>的行.所以我虽然这个收集器并不能很好地并行工作:
private static Collector<String, ?, List<String>> oddLines() {
int[] counter = {1};
return Collector.of(ArrayList::new,
(l, line) -> {
if (counter[0] % 2 == 1) l.add(line);
counter[0]++;
},
(l1, l2) -> {
l1.addAll(l2);
return l1;
});
}
Run Code Online (Sandbox Code Playgroud)
但它的确有效.
编辑:它实际上没有工作; 我被我的输入集太小而无法触发任何并行性这一事实所迷惑; 见评论中的讨论.
我认为这是行不通的,因为我想到了以下两个执行计划.
counter数组在所有线程之间共享.线程t1读取Stream的第一个元素,因此满足if条件.它将第一个元素添加到其列表中.然后在他有时间更新数组值之前停止执行.
线程t2,从流的第4个元素开始,将其添加到列表中.所以我们最终得到了一个非想要的元素.
当然,既然这个收藏家似乎有效,我猜它不会那样.而且无论如何更新都不是原子的.
在这种情况下,更新没有更多的问题,但没有什么能阻止线程t2不会从流的第4个元素开始.所以他也不像那样工作.
有人能解释我基本上它是如何工作的以及为什么我的收藏家在并行运行时工作?
非常感谢你!
java ×10
java-8 ×6
collectors ×2
comparator ×2
eclipse ×2
java-stream ×2
c# ×1
comparable ×1
constructor ×1
datetime ×1
eclipse-luna ×1
java-time ×1