标签: java-8

为什么没有Duration.ofWeeks()?

根据这个答案,没有一个Duration.ofMonths()

因为一个月的长度不一样.

但为什么不存在Duration.ofWeeks()呢?一周的长度不变,至少不超过一天的长度.我们确实有一个Duration.ofDays().

那么,这有充分的理由吗?

java datetime java-8 java-time

1
推荐指数
1
解决办法
137
查看次数

是否有一种方法/解决方法来增加java8中的int

我有以下方法执行树遍历并执行一些操作:

public int method(){
    int retVal;
    Tree t;
    //initialization of t
    t.accept(() -> ++retVal)); //error, variable is not 
                               //effectively final
    return retVal;
 }
Run Code Online (Sandbox Code Playgroud)

哪里

public interface Visitor{
    public void visitNode();
}

public interface Tree{
     /**
      * Traverses this tree and perform some action in each node
      */
    public void accept(Visitor v); 

    //other methods omitted
}
Run Code Online (Sandbox Code Playgroud)

有办法解决这个问题吗?

java lambda java-8

1
推荐指数
1
解决办法
110
查看次数

Java 8可选orElse而isPresent

orElse对可选方法很困惑.我使用了以下代码,orElse尽管存在可选值,但每次调用该代码:

Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile, type));
Run Code Online (Sandbox Code Playgroud)

如果我将代码重写为以下内容,ifPresent则选择正确的路径():

Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.isPresent() ? ons.get() : createNotificationSettings(profile, type);
Run Code Online (Sandbox Code Playgroud)

我认为orElse在第二种情况下就像我的例子一样.我错过了什么?

optional java-8

1
推荐指数
1
解决办法
349
查看次数

Java 8可选

我想检查一个特定的对象大小是否大于0.如果它大于0然后我想创建一个可选对象,如果没有,那么我想返回一个Optional空.这是java代码的长版本:

if(fooA.size>0) {
    return Optional.of(new Foo());
} else {
    return Optional.empty();
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用java 8的可选库将其压缩成一行?

java optional java-8

1
推荐指数
2
解决办法
1650
查看次数

返回方法参考

我在Java 8中玩.如何返回方法引用?

我能够返回lambda而不是方法引用.

我的尝试:

public Supplier<?> forEachChild(){
     return new ArrayList<?>::forEach;
}
Run Code Online (Sandbox Code Playgroud)

要么

public Function<?> forEachChild(){
     return new ArrayList<?>::forEach;
}
Run Code Online (Sandbox Code Playgroud)

java-8 method-reference

1
推荐指数
1
解决办法
1252
查看次数

使用Java 8 Stream对HashMap字符串值进行排序不起作用

我正在使用问题的解决方案对a中的String值进行排序LinkedHashMap.然而,排序根本不起作用.这是我写的代码.

Map<Integer, String> sortedMap = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry<Integer, String>::getKey, 
                    Map.Entry<Integer, String>::getValue));

myMap = new LinkedHashMap<Integer, String>(sortedMap);
Run Code Online (Sandbox Code Playgroud)

奇怪的是,Integer当使用两者comparingByValuecomparingByKey方法时,它正在对键进行排序.所以它肯定是排序,而不是String值,但在两种情况下都是Integer键.我不明白我在这里做错了什么.

java sorting hashmap java-8 java-stream

1
推荐指数
1
解决办法
1078
查看次数

if语句替代Java 8

有这样的功能:

public void toDo(Req req){

    if(req.getSection().equals("A")) {
        return execA(req);
    }

    if(req.getSection().equals("B")) {
        return execB(req);
    }

    if(req.getSection().equals("N")) {
        return execN(req);
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何简化它?一般的想法,如何排除if语句的识别类型的功能 - 字符串 - A,B,N.Java 8的任何解决方案都与Scala模式匹配?

java lambda if-statement java-8

1
推荐指数
2
解决办法
2496
查看次数

Java中一个对象与另一个对象的弱关联?

我上课的时候

class MyClass1 {
    MyClass2 member;
}
Run Code Online (Sandbox Code Playgroud)

ans它是垃圾收集,然后member也有资格垃圾收集.

我可以模拟同样的关系Map吗?

所以,我希望一个带有弱引用键的地图.即地图本身不应该阻止垃圾收集密钥.一旦密钥被垃圾收集,其关联值也有资格进行垃圾收集.

这可能吗?

UPDATE

这只是WeakHashMap

java dictionary garbage-collection weak-references java-8

1
推荐指数
1
解决办法
88
查看次数

使用Java 8从列表中有选择地删除前N个

看到问题的评论。有选择地删除N个元素(条件是列表元素匹配“删除”)

List<String> mylist = new ArrayList<>();
mylist.add("remove");
mylist.add("all");
mylist.add("remove");
mylist.add("remove");
mylist.add("good");
mylist.add("remove");

//  Remove first X "remove".
//  if X is 2, then result list should be "all, remove, good, remove"
//  Use java 8 features only, possibly single line code.
//  Please don't answer with looping, iterating, if conditions etc.
//  Answer should use JDK 8 new features.
Run Code Online (Sandbox Code Playgroud)

lambda list java-8 java-stream

1
推荐指数
1
解决办法
2139
查看次数

Java - 为什么我的静态变量被设置为null?

编辑1:我想我可能已经弄明白了.

这是我的initialize()方法

public void initialize(URL location, ResourceBundle resources) {
    groupList.setItems(createGroupFilter());
    groupList.getSelectionModel().selectedItemProperty().addListener(obs -> {
        Group.setSelectedGroup(groupList.getSelectionModel().getSelectedItem());
        handleGroupSelected();
    });
Run Code Online (Sandbox Code Playgroud)

我认为当我重新加载groupList ListView时,正在调用这个selectedItemProperty侦听器并将其设置为null.

我通过在侦听器中添加if条件来修复此问题:

public void initialize(URL location, ResourceBundle resources) {
    groupList.setItems(createGroupFilter());
    groupList.getSelectionModel().selectedItemProperty().addListener(obs -> {
        if(groupList.getSelectionModel().getSelectedItem() != null) {
            Group.setSelectedGroup(groupList.getSelectionModel().getSelectedItem());
            handleGroupSelected();
        }
    });
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我的静态'selectedGroup'变量被设置为null,我无法弄清楚原因.

我已经进行了以下故障排除.

我有一个名为'refresh()'的方法,它调用一个名为'createGroupFilter()'的方法.我已经包含了以下System.out.println语句,以便查看变量何时变为空.

private void refresh() {
    System.out.println("before groupList.setItems(createGroupFilter()); "  + Group.getSelectedGroup()); //TROUBLESHOOTING
    groupList.setItems(createGroupFilter());
    System.out.println("after groupList.setItems(createGroupFilter()); "  + Group.getSelectedGroup()); //TROUBLESHOOTING
    if(Group.getSelectedGroup() != null) {
        groupList.getSelectionModel().select(Group.getSelectedGroup());
        int n = groupList.getSelectionModel().getSelectedIndex();
        groupList.getFocusModel().focus(n);
        groupList.scrollTo(n);
        userList.setItems(createUserFilter());
        if(User.getSelectedUser() != null) {
            userList.getSelectionModel().select(User.getSelectedUser());
        }
    }
}

private FilteredList<Group> …
Run Code Online (Sandbox Code Playgroud)

java static javafx java-8 javafx-8

1
推荐指数
1
解决办法
560
查看次数