简体   繁体   English

JAVA-将数据从结果集中存储到哈希图中并进行汇总

[英]JAVA - Storing data from result set to hashmap and aggregating them

as the title, I'd like to store data from result set to hash map and then use them for further processing (max, min, avg, grouping). 作为标题,我想将结果集中的数据存储到哈希图,然后将其用于进一步处理(最大,最小,平均,分组)。

So far, I achieved this by using a proper hash map and implementing each operation from scratch - iterating over the hash map (key, value) pairs. 到目前为止,我通过使用适当的哈希图并从头开始执行每个操作-遍历哈希图(键,值)对来实现此目的。

My question is: does it exist a library that performs such operations? 我的问题是:是否存在执行此类操作的库? For example, a method that computes the maximum value over a List or a method that, given two same-size arrays, performs a "index-to-index" difference. 例如,一种在List上计算最大值的方法,或者在给定两个相同大小的数组的情况下执行“索引到索引”差异的方法。

Thanks in advance. 提前致谢。

Well there is the Collection class for instance. 好吧,例如有Collection类。 There is a bunch of useful static methods but you'll have to read and choose the one you need. 有很多有用的静态方法,但是您必须阅读并选择所需的方法。 Here is the documentation: 这里是文档:

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html

This class consists exclusively of static methods that operate on or return collections. 此类仅包含对集合进行操作或返回集合的静态方法。

Example: 例:

        List<Integer> list = new ArrayList<>();
        List<String> stringList = new ArrayList<>();

        // Populate the lists
        for(int i=0; i<=10; ++i){
            list.add(i);
            String newString = "String " + i;
            stringList.add(newString);
        }
        // add another negative value to the integer list
        list.add(-1939);

        // Print the min value from integer list and max value form the string list.

        System.out.println("Max value: " + Collections.min(list));
        System.out.println("Max value: " + Collections.max(stringList));

The output will be: 输出将是:

run:
Max value: -1939
Max value: String 9
BUILD SUCCESSFUL (total time: 0 seconds)

Similar question, however, was answered before for example here: how to get maximum value from the List/ArrayList 但是,在这里,例如,在此之前已回答过类似的问题: 如何从List / ArrayList获得最大值

There are some usefull functions in Collections API already. Collections API已经有一些有用的功能。

For example max or min 例如maxmin

Collections.max(arrayList);

Please investigate collections documentation to see if there is a function that you need. 请调查收集文档以查看是否需要您的功能。 Probably there woulde be. 可能会有。

You can use java 8 streams for this. 您可以为此使用java 8流。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Testing {
    public static void main(String[] args) {

        //List of integers
    List<Integer> list = new ArrayList<>();
    list.add(7);
    list.add(5);
    list.add(4);
    list.add(6);
    list.add(9);
    list.add(11);
    list.add(12);

    //get sorted list using streams
    System.out.println(list.stream().sorted().collect(Collectors.toList()));

        //find min value in list
        System.out.println(list.stream().min(Integer::compareTo).get());

        //find max value in list
        System.out.println(list.stream().max(Integer::compareTo).get());

        //find average of list
        System.out.println(list.stream().mapToInt(val->val).average().getAsDouble());


        //Map of integers
        Map<Integer,Integer> map = new HashMap<>();

        map.put(1, 10);
        map.put(2, 12);
        map.put(3, 15);

        //find max value in map
        System.out.println(map.entrySet().stream().max((entry1,entry2) -> entry1.getValue() > entry2.getValue() ? 1: -1).get().getValue());

        //find key of max value in map
        System.out.println(map.entrySet().stream().max((entry1,entry2) -> entry1.getValue() > entry2.getValue() ? 1: -1).get().getKey());

        //find min value in map
        System.out.println(map.entrySet().stream().min((entry1,entry2) -> entry1.getValue() > entry2.getValue() ? 1: -1).get().getValue());

        //find key of max value in map
        System.out.println(map.entrySet().stream().min((entry1,entry2) -> entry1.getValue() > entry2.getValue() ? 1: -1).get().getKey());

        //find average of values in map
        System.out.println(map.entrySet().stream().map(Map.Entry::getValue).mapToInt(val ->val).average().getAsDouble());
    }



}

Keep in mind that it will only work if your system has jdk 1.8 .For lower version of jdk streams are not supported. 请记住,它仅在系统具有jdk 1.8时才起作用。对于较低版本的jdk流,不支持。

In Java8 there are IntSummaryStatistics , LongSummaryStatistics , DoubleSummaryStatistics to calculate max , min , count , average and sum 在Java8中,有IntSummaryStatisticsLongSummaryStatisticsDoubleSummaryStatistics可以计算maxmincountaveragesum

public static void main(String[] args) {
    List<Employee> resultSet = ...
    Map<String, DoubleSummaryStatistics> stats = resultSet.stream().collect(Collectors.groupingBy(Employee::getName, Collectors.summarizingDouble(Employee::getSalary)));
    stats.forEach((n, stat) -> System.out.println("Name " + n + " Average " + stat.getAverage() + " Max " + stat.getMax())); // min, sum, count can also be taken from stat
}

static class Employee {
    String name;
    Double salary;

    public String getName() {
        return name;
    }

    public Double getSalary() {
        return salary;
    }
}

对于max,min,avg,您可以使用Java 8及其流处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM