使用流填充地图中的对象列表

时间:2019-11-26 14:11:50

标签: java java-stream

我有下面的地图和一个字符串

/**
4->"welcome"
3->"to"
2->"my"
1->"blog"
*/

Map<Integer, String> myMap = ImmutableMap.of(4, "welcome", 3, "to", 2, "my",1,"blog");
String s= "welcome to my blog everyone"

现在我需要根据降序从字符串中删除单词来填充下面的对象列表(该地图已经降序排列)

{
   "level": 1,
   "delete":["welcome"],
   "modString":"to my blog everyone" 
}
{
   "level": 2,
   "delete":["welcome","to"],
   "modString":"my blog everyone" 
}
{
   "level": 3,
   "delete":["welcome","to","my"],
   "modString":"blog everyone" 
}
{
   "level": 4,
   "delete":["welcome","to","my","blog"],
   "modString":"everyone" 
}

列表的类型为“删除”

public class Delete {
    private Integer level;
    private String modString;
    private List<String> delete;

    public Delete(
            Integer level,
            String modString,
            List<String> delete) {
        this.level = level;
        this.modString = modString;
        this.delete = delete;
    }

 //getters and setters

    }

}

我可以通过迭代地图来做到这一点,但我一直在考虑是否可以使用Streams做到这一点。

1 个答案:

答案 0 :(得分:0)

我不太了解地图按键的用途及其与级别的关系。但是我假设您想解决lambda内必须为final的java变量的问题。为此,您可以在同一包中使用java.util.concurrent.atomic.AtomicReference或其他类。

final AtomicReference<String> modString = new AtomicReference<>(s);
final Comparator<Map.Entry<Integer, String>> comparing = Comparator.comparing(Map.Entry::getKey);
final List<String> deletedOnes = new ArrayList<>(myMap.size());
final List<Delete> result = myMap.entrySet().stream().sorted(comparing.reversed()).map(entry -> {
    deletedOnes.add(entry.getValue());
    modString.set(modString.get().replaceFirst(entry.getValue(), "").trim());
    return new Delete(myMap.size() - entry.getKey() + 1, modString.get(), new ArrayList<>(deletedOnes));
}).collect(Collectors.toList());