小编ETO*_*ETO的帖子

从内部匿名类访问外部匿名类的方法

我使用一个实例化另一个匿名类的方法实例化一个匿名类,并且从这个内部匿名类我想调用一个属于外部匿名类的方法.为了说明它,假设我有这个界面:

interface ReturnsANumber {
    int getIt();
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的代码中的某个地方,我这样做:

    ReturnsANumber v = new ReturnsANumber() {
            int theNumber() {
                return 119;
            }

            public int getIt() {

                // In a modern version of Java, maybe I could do
                //   var a = this;
                // and then call a.theNumber();

                ReturnsANumber w = new ReturnsANumber() {
                        int theNumber() {
                            return 1;
                        }

                        public int getIt() {
                            return this.theNumber();
                        }
                    };

                return w.getIt();
            }
        };
    System.out.println("The number is " + v.getIt());
Run Code Online (Sandbox Code Playgroud)

问题: 在最里面的方法中getIt,我想调用theNumber() …

java methods anonymous-class java-8 method-reference

22
推荐指数
3
解决办法
920
查看次数

Comparator.nullsLast不会避免NullPointerException

我想通过一个可空字段对对象列表进行排序.

为了避免NullPointerexception我使用Comparator.nullsLast.但例外情况仍然存在:

public class Test {

    public static void main(String[] args) {
        List<Bean> l = new ArrayList<>();
        for (int i=0;i<5;i++) {
            Bean b = new Bean("name_"+i,i);
            l.add(b);
        }
        l.get(2).setVal(null);
        System.out.println(l);
        Collections.sort(l, Comparator.nullsLast(Comparator.comparing(Bean::getVal)));
        System.out.println(l);
    }

    static class Bean{
        String name;
        Integer val;
        // omit getters & setters & constructor
    }

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能对这种清单进行排序?

java collections comparator java-8 java-stream

9
推荐指数
2
解决办法
1905
查看次数

如果使用Java 8 Streams列表为空,则返回默认列表?

有什么办法可以将以下操作作为一组流操作来执行,而不是显式地检查committedProducts 是否为空,然后返回默认列表,否则返回过滤后的列表

public List<Product> getRecommendedProducts() {
    List<Product> recommendedProducts 
        = this.newProducts
              .stream()
              .filter(isAvailable)
              .collect(Collectors.toList());

    if (recommendedProducts.isEmpty()) {
        return DEFAULT_PRODUCTS;
    }

    return recommededProducts;
}
Run Code Online (Sandbox Code Playgroud)

java collections optional java-8 java-stream

9
推荐指数
2
解决办法
122
查看次数

迭代和复制HashMap值的有效方法

我想转换:

Map<String, Map<String, List<Map<String, String>>>> inputMap 
Run Code Online (Sandbox Code Playgroud)

到:

Map<String, Map<String, CustomObject>> customMap
Run Code Online (Sandbox Code Playgroud)

inputMap在配置中提供并准备就绪,但我需要customMap格式化。CustomObject 将通过List<Map<String, String>>在函数中使用几行代码来派生。

我已经尝试了迭代输入映射和复制 customMap 中的键值的正常方法。有没有使用 Java 8 或其他一些快捷方式来做到这一点的有效方法?

Map<String, Map<String, List<Map<String, String>>>> configuredMap = new HashMap<>();
Map<String, Map<String, CustomObj>> finalMap = new HashMap<>();


for (Map.Entry<String, Map<String, List<Map<String, String>>>> attributeEntry : configuredMap.entrySet()) {
    Map<String, CustomObj> innerMap = new HashMap<>();
    for (Map.Entry<String, List<Map<String, String>>> valueEntry : attributeEntry.getValue().entrySet()) {
        innerMap.put(valueEntry.getKey(), getCustomeObj(valueEntry.getValue()));
    }
    finalMap.put(attributeEntry.getKey(), innerMap);
}

private CustomObj getCustomeObj(List<Map<String, String>> list) {
    return new CustomObj();
}
Run Code Online (Sandbox Code Playgroud)

java collections java-8 java-stream

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

使用Java 8按两个字段对对象进行分组

我有一个问题,用Java 8分组两个值.

我的主要问题是关于分组两个字段,我正确地组合了一个字段,getNameOfCountryOrRegion()但现在我对groupingBy另一个被调用的字段感兴趣leagueDTO.

Map<String, List<FullCalendarDTO>> result = countryDTOList.stream()
               .collect(Collectors.groupingBy(
                             FullCalendarDTO::getNameOfCountryOrRegion));
Run Code Online (Sandbox Code Playgroud)

以下课程:

public class FullCalendarDTO  {
    private long id;
    private TeamDTO localTeam;
    private TeamDTO visitorTeam;
    private LocationDTO location;   
    private String leagueDTO;       
    private String timeStamp;
    private String nameOfCountryOrRegion;
}
Run Code Online (Sandbox Code Playgroud)

结果将通过分组nameOfCountryOrRegionleagueDTO.

java collections grouping java-8 java-stream

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

有没有一种方法可以检查Stream是否包含所有集合元素?

例如,我需要类似的东西:

Collection<String> collection = /* ... */;
Stream<Object> stream = /* ... */;
boolean containsAll = stream.map(Object::toString).containsAll(collection);
Run Code Online (Sandbox Code Playgroud)

当然,我可以Collection使用collect()方法和调用将流的所有元素累积到另一个元素中Collection.containsAll(),但是如果流太大并且处理所有元素的效率低下怎么办?

java collections contains java-8 java-stream

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

编写一个程序,使用`replace`方法在一个字符串中交换字母"e"和"o"

例如,如果我有Hello World它应该成为Holle Werld.我怎么能用这个String.replace呢?我已经尝试过,"Hello World".replace("e","o")但我只能得到Hollo World,如果我再次使用它,我会得到Helle Werld.

java collections java-8 java-stream

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

在文件系统中搜索数据的性能优化

我有一个网络相关存储,其中大约有500万个txt文件与大约300万个交易相关.总数据大小约为3.5 TB.我必须在该位置搜索以查找交易相关文件是否可用,并且必须将两个单独的报告作为"可用文件"和"不可用文件"的CSV文件.我们仍然在JAVA 6.我面临的挑战因为我必须递归搜索该位置,因为巨大的尺寸,我需要大约2分钟才能在该位置进行搜索.我正在使用Java I/O API来递归搜索,如下所示.有什么方法可以改善性能吗?

File searchFile(File location, String fileName) {
     if (location.isDirectory()) {
         File[] arr = location.listFiles();
         for (File f : arr) {
             File found = searchFile(f, fileName);
             if (found != null)
                 return found;
         }
     } else {
         if (location.getName().equals(fileName)) {
             return location;
         }
     }
     return null;
}
Run Code Online (Sandbox Code Playgroud)

java optimization search file

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

在一个流中过滤和设置()

所以我有一些我正在玩的示例代码,试图在下面找出这个逻辑.它只是一个大的主要方法和两个POJO,但它会运行.我正在调试以在终止点获取值.

public class Main {

    public static void main(String[] args) {

        obj1 obj1 = new obj1();
        obj1 obj12 = new obj1();

        obj2 obj2 = new obj2();
        obj2 obj22 = new obj2();

        obj1.id = 123L;
        obj1.carId = 1234L;
        obj12.id = 123L;
        obj12.carId = 1234L;

        obj2.carId = 1234L;
        obj22.carId = 12345L;

        ArrayList<obj1> obj1Arr = new ArrayList<>();
        ArrayList<obj2> obj2Arr = new ArrayList<>();

        obj1Arr.add(obj1);
        obj1Arr.add(obj12);

        obj2Arr.add(obj2);
        obj2Arr.add(obj22);

        List<obj2> newCarList= obj2Arr.stream()
                .filter(anObjOf2 -> obj1Arr
                        .stream()
                        .anyMatch(carReg -> carReg.getCarId().equals(anObjOf2.getCarId())))
                .collect(Collectors.toList());
    }
}
Run Code Online (Sandbox Code Playgroud)

POJO1:

public class obj1 …
Run Code Online (Sandbox Code Playgroud)

java collections java-8 java-stream

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

java.util.IllegalFormatConversionException: f != java.lang.Integer

我正在尝试创建一个简单的java程序,该程序读取浮点数,使用欧拉数方程计算它,然后将结果从double转换为int。我可以让它编译而不会出现错误,但在输入浮点数后出现错误:

\n
nB = Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer\n    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)\n    at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)\n    at java.util.Formatter$FormatSpecifier.print(Unknown Source)\n    at java.util.Formatter.format(Unknown Source)\n    at java.io.PrintStream.format(Unknown Source)\n    at java.io.PrintStream.printf(Unknown Source)\n    at Ex4.main(Ex4.java:16)\n
Run Code Online (Sandbox Code Playgroud)\n

它只有几行代码,我刚刚创建了一个运行良好的类似程序,所以我不明白这里出了什么问题!我认为这可能与欧拉数上的行有关,因为我还没有完全理解所有数学函数,但我在以完全相同的方式使用 \xcf\x80 之前就很好了。还是因为最后的转换步骤错误?抱歉,如果这是非常明显的事情,我已经尽力调试它很多次了,但每当我更改某个部分时,我认为这可能是问题所在,我最终会遇到更多错误。这是代码:

\n
import static java.lang.Math.*;\nimport java.util.Scanner;\n\nclass Ex4\n{\n    public static void main( String [ ] args)\n    {\n        Scanner input = new Scanner(System.in);         //import scanner and ask user to input number\n        System.out.print("Please enter a floating-point number: ");\n        double nA = input.nextDouble();     \n\n        double nB = Math.pow(E, nA); …
Run Code Online (Sandbox Code Playgroud)

java format string-formatting java-8

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