Java 8- Lambda表达式和流可在HashMap的HashMap上进行迭代

时间:2018-12-03 23:40:42

标签: java lambda java-8 java-stream

我需要使用lambda表达式遍历HashMap的HashMap,并过滤掉一些不需要的条目。我尝试了几种方法,但似乎没有用。下面是地图的结构。

Map<String, Map<Date, String>> sensor_tags = new HashMap<String, Map<Date,String>>();

从此地图中,我需要删除传感器数据早于特定日期(日期是内部地图的键)的条目。以下是地图sensor_tags-

的示例数据
String tagName = "zoneSensor";
Map<Date, String> values= new HashMap<Date, String>();

// (1st entry for tag 1) --> date is day before yesterday
Calendar datekey1 = Calendar.getInstance();
datekey1.set(2018, 12, 01, 12, 30, 45);
values.put(datekey1.getTime(), "ON");

// (2nd entry for tag 1) --> date is yesterdys date
Calendar datekey = Calendar.getInstance();
datekey.set(2018, 12, 02, 12, 30, 45);
values.put(datekey.getTime(), "OFF");

// (3rd entry for tag 1) --> date is today
Calendar instance = Calendar.getInstance();
instance.set(2018, 12, 03, 12, 30, 45);
values.put(instance.getTime(), "ON");

//(4th entry for tag 1)--> date is today + 10 sec
instance.add(Calendar.MILLISECOND, 10000);
sensor_tags.put(tagName, values);

values.put(instance.getTime(), "ON");
sensor_tags.put(tagName, values);

// 5th entry for tag2
tagName = "zoneSensor1";
values= new HashMap<Date, String>();
values.put(Calendar.getInstance().getTime(), "NORMAL");
sensor_tags.put(tagName, values);

//code in java 7
for (final Entry<String, Map<Date, String>> entry : sensor_tags.entrySet()) {
            final Iterator<Date> iter = entry.getValue().keySet().iterator();
            while (iter.hasNext()) {
                final Date date = iter.next();
                if (date.before(givendate)) {
                    iter.remove();
                }
        }
}

// code tried in java 8 (I am a beginner here :-) )
 sensor_tags
            .entrySet()
            .stream()
            .map(Map.Entry::getValue) // get an inner map
            .filter(value -> ((Date)value).before(datekey.getTime()));

如何遍历和过滤内部地图的数据?另外,一旦数据被过滤,我就需要保留地图的结构,因此输出仅需要收集在Map<String, Map<Date, String>>中。

3 个答案:

答案 0 :(得分:5)

如果要修改现有地图,则不需要流。只需循环并调用removeIf()

sensor_tags.values().forEach(
        m -> m.keySet().removeIf(datekey.getTime()::after));

答案 1 :(得分:2)

如果您不想修改现有地图,那么就不需要流,您可以简化命令式方法来实现:

for (final Map<Date, String> v : sensor_tags.values()) {
      v.keySet().removeIf(d -> d.before(datekey.getTime()));
}

如果您不想修改现有地图,则可以执行以下操作:

Map<String, Map<Date, String>> result = sensor_tags.entrySet()
     .stream()
     .collect(toMap(
         Map.Entry::getKey, 
         e -> e.getValue().entrySet().stream()
                                     .filter(a -> !a.getKey().before(datekey.getTime()))
                                     .collect(toMap(Map.Entry::getKey, 
                                                    Map.Entry::getValue))));

答案 2 :(得分:1)

我为您制作了这两种方法。第一个创建新的哈希图,第二个使用所需的过滤动态更改您的Hashmap。我没有检查极端情况,但它们似乎有效。希望这会有所帮助:

保留您的哈希图

private Map<String, Map<Date, String>> getFilteredResultsKeeping(Map<String, Map<Date, String>> sensor_tags,
        Date givendate) {
    return sensor_tags.entrySet().stream()
            .map(sensorValue -> new SimpleEntry<>(sensorValue.getKey(),
                    sensorValue.getValue().entrySet().stream()
                            .filter(sensor -> !sensor.getKey().before(givendate))
                            .map(sensor -> sensor.getKey())
                            .collect(toMap(date -> date, date -> sensorValue.getValue().get(date)))))
            .collect((toMap(SimpleEntry::getKey, SimpleEntry::getValue)));
}

更改您的哈希图

private Map<String, Map<Date, String>> getFilteredResultsRemoving(Map<String, Map<Date, String>> sensor_tags,
        Date givendate) {
    return sensor_tags.entrySet().stream()
            .peek(sensorValue -> {
                List<Date> invalidDates = sensorValue.getValue().entrySet().stream()
                        .map(sensor -> sensor.getKey())
                        .filter(date -> date.before(givendate)).collect(Collectors.toList());
                invalidDates.forEach(date -> sensorValue.getValue().remove(date));
            })
            .collect((toMap(Entry::getKey, Entry::getValue)));
}