-2

I have the below map of and a string

/** 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" 

Now I need to poulate the below object list by deleting the words from the string based on the order in decending order(the map is already sorted decending)

{ "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" } 

The list has the type Delete

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 } } 

I can do it by iterating the map but I was thinking if this can be done using Streams.

1

1 Answer 1

0

I don't quite get the purpose of the map's keys and their relation to level. But I assume you want a solution to java's variables inside lambdas having to be final. For that purpose you can use java.util.concurrent.atomic.AtomicReference or other classes in the same package.

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()); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.