小编Tag*_*eev的帖子

当将Optional.isPresent和Optional.get称为“不同”级别时,显示警告?

在以下代码段中,我的Foo类带有始终返回的相同实例的方法Optional。然后我有另一个OneMoreClass使用Foo类的类。

您可以从源代码中看到调用get()方法是安全的,method1因为始终在中检查该方法method2

IntelliJ IDEA仍然显示警告的问题(您只需将此代码段复制到IDEA,您将看到此问题)。

public class Example {

    public static class Foo {

        private final Optional<String> value = Optional.empty();

        public Optional<String> bar() {
            return value;
        }
    }

    public static class OneMoreClass {
        void method1(final Foo foo) {
            method2(foo);
            System.out.println(foo.bar().get()); // here the warning is shown in IntelliJ IDEA: 
                                                 // "Optional.get()" without "isPresent()" check
        }

        void method2(final Foo foo) {
            if (!foo.bar().isPresent()) {
                throw new IllegalArgumentException("No value"); …
Run Code Online (Sandbox Code Playgroud)

java intellij-idea optional java-8

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

为什么我不能在JAVA项目中实现Streams功能?

我是JAVA编程的初学者.最近,我尝试使用s 的map&filter功能,Stream如下面的代码所示.

    List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
    long count = strList.stream().filter(x -> x.isEmpty()).count();
    System.out.printf("List %s has %d empty strings %n", strList, count);
Run Code Online (Sandbox Code Playgroud)

但是,编译器总是抱怨我需要"创建局部变量x".

也许我失去了一些基本步骤,这些步骤太容易在Google上找到任何相关的讨论.

我的JAVA编译器版本是J2SE 1.5,我将java.util.stream.*导入到我的文件中.

谢谢!

java functional-programming local-variables compiler-warnings java-stream

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

Java流排序不起作用

我有一个

HashMap<String,Integer> map 
Run Code Online (Sandbox Code Playgroud)

我希望按值按降序排序:

HashMap<String,Integer> topSorted = new HashMap<>();

//sort map in descending order
Stream<HashMap.Entry<String,Integer>> st = map.entrySet().stream();
st.sorted(Comparator.comparing((HashMap.Entry<String,Integer> e) -> e.getValue()).reversed())
        .forEach(e -> topSorted.put(e.getKey(),e.getValue()));
Run Code Online (Sandbox Code Playgroud)

但topsorted仍然与地图相同,根本没有进行排序

有人可以解释我做错了什么

java sorting java-8 java-stream

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

找不到符号类Random

当我运行此代码时,它在技术上应该没有任何问题,但我不断收到错误"无法找到符号随机"在代码的开头是否需要输入任何内容!?

public class RandomNumbers {

    public static void main(String[] args) {
        Random r = new Random();
        System.out.println("First number: " + r.nextInt(100));
        System.out.println("Second number: " + r.nextInt(100));
        System.out.println("Third number: " + r.nextInt(100));
        System.out.println("Fourth number: " + r.nextInt(100));
        System.out.println("Fifth number: " + r.nextInt(100));
    }
}
Run Code Online (Sandbox Code Playgroud)

java random

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

java流performace用于查找列表中的最大元素

我编写了一个简单的程序来与流的性能进行比较,以查找整数的最大形式列表。令人惊讶的是,我发现“流方式”的性能是“通常方式”的1/10。难道我做错了什么?是否有条件限制哪种Stream方法无效?有人能对此行为做出一个很好的解释吗?

“流方式”花费了80毫秒“流方式”花费了15毫秒请在下面找到代码

public class Performance {

public static void main(String[] args) {

    ArrayList<Integer> a = new ArrayList<Integer>();
    Random randomGenerator = new Random();
    for (int i=0;i<40000;i++){
        a.add(randomGenerator.nextInt(40000));
    }
    long start_s = System.currentTimeMillis( );

            Optional<Integer> m1 = a.stream().max(Integer::compare);

    long diff_s = System.currentTimeMillis( ) - start_s;
    System.out.println(diff_s);


    int e = a.size();
    Integer m = Integer.MIN_VALUE;

    long start = System.currentTimeMillis( );
    for(int i=0; i < e; i++) 
      if(a.get(i) > m) m = a.get(i);

    long diff = System.currentTimeMillis( ) - start;
    System.out.println(diff);


}
Run Code Online (Sandbox Code Playgroud)

}

java performance java-8 java-stream

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

Java 8流forEach

我试图迭代对象的ArrayList并打印出列表中每个对象的'name'属性.但是,即使我在Person类中有名称的getter方法,我也无法访问该对象的属性.这是一些代码:

 ArrayList persons = new ArrayList<>();
 persons.add(new Person("Name","Age"));
 persons.add(new Person("Name1","Age1"));
 persons.add(new Person("Name2","Age2"));

persons
 .stream()
 .forEach(e -> System.out.println(e.getName()));   //giving an error

  forEach(e -> System.out.println(e));  //no error
Run Code Online (Sandbox Code Playgroud)

它不允许我这样做.我只能在打印命令中使用'e',它打印对象的参考号.

任何帮助表示赞赏:)

java java-8 java-stream

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

Java Stream.sorted()给出了错误的结果

我有列表{"100","5","1","300","7"},当我stream().sorted()用于此列表时,它给了我以下结果{"1","100","300","5","7"}.看起来它只按第一个数字排序.怎么了?

ArrayList<String> list = new ArrayList<>(Arrays.asList(
            "100","5","1","300","7"
));

list.stream().sorted().forEach(e -> System.out.println(e));
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

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

使用十六进制代码循环打印 Unicode 字符

我收到以下代码的非法 unicode 转义。

 for(int i=3400;i<4000;i++)
   System.out.println("\u" + i );
Run Code Online (Sandbox Code Playgroud)

\u3400如果我在得到输出而不是实际的 unicode 字符之前添加斜杠。

我想在循环中打印 unicode 字符。unicode 字符也是十六进制代码。如何循环访问十六进制代码并打印所有 unicode 字符。

java string unicode hex unicode-escapes

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

为什么这个List <>抛出NullPointerException?

所以我一直坐在这段代码上面一段时间,准备好NullPointerException线程,仍然无法弄清楚我的代码出了什么问题,所以我转向你.

public class Main {
public static void main(String[] args){     
    /* Making catalog, loading last state */
    Collection catalog = new Collection();      
    try {
        catalog.readFromFile();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
catalog.addShip(new Ship("ABC123", "John", "Suzuki", 50));
 }
}
Run Code Online (Sandbox Code Playgroud)

我的Collection类看起来像这样:

public class Collection {
    private List<Ship> shipList;
    private String fileName = "catalog.txt";
    private int income;
    private int space;

public Collection() {
    shipList = new ArrayList<Ship>();
    income = 0;
    space = 500;
    File f = new File("catalog.txt");
    if(!f.exists()) { …
Run Code Online (Sandbox Code Playgroud)

java nullpointerexception

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

流分组:子列表到唯一的父列表

我正在寻找一种简洁有效的方法来从使用Java 8流的子项列表中获取唯一父项列表.

对于示例,我有两个简单的类:

public class Child{
  private Parent parent;
  public Child(Parent parent){
    this.parent = parent;
  }
  public Parent getParent(){
    return this.parent;
  }
}

public class Parent{
  private List<Child> children;
  public Parent(){
    this.children = new ArrayList<Child>();
  }
  public void addChild(Child child){
    this.children.add(child);
  }
}
Run Code Online (Sandbox Code Playgroud)

首先,我从某种方法获得Child对象的列表.
孩子可能属于多个父母,可能有父母碰撞.

List<Child> children = getChildren();
Run Code Online (Sandbox Code Playgroud)

然后 :

List<Parent> uniqueParents = children
  .stream()
  .collect(Collectors.groupingBy(Child::getParent))
  .keySet()
  .stream()
  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

所以它有效,但我想避免双流并收集.

这可能直接在一个流中吗?

java collections java-stream

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