How to calculate the length of multiple lines

I have a line like this:

Hi, my name is $ name $; I have $ years of age $ and I love to play $ sport $ and I live in $ country $!

And I want to return the length of every word between $ in the Map, for my example the map should be:

  • name β†’ 4
  • years β†’ 5
  • sports β†’ 5
  • country β†’ 7

At first I thought about creating recursive calls in my function, but I haven't found a way to do it?

+3


source to share


4 answers


You can use Pattern and Matcher this will return all matched instances, then you can iterate over the results and add them to the map.



String x = "Hey my name is $name$; I have $years$ years old," + 
           "and I love play $sport$ and I live in $country$ !";
Pattern p = Pattern.compile("\\$\\w+\\$");
Matcher m = p.matcher(x);
Map<String, Integer> map = new LinkedHashMap<>();

while(m.find()) {
  String in = m.group().substring(1,m.group().length()-1);
  map.put(in, in.length());
}

      

+5


source


Remember, maps don't allow duplicates ... if that's okay for you, then with streams and a regex you can get this:

String x = "Hey my name is $name$; I have $years$ years old, and I love play $sport$ and I live in $country$ !";
//regex to get the words between $
Matcher m = Pattern.compile("\\$(.*?)\\$").matcher(x);
List<String> l = new ArrayList<>();
//place those matchs in a list
while (m.find()) {
        l.add(m.group(1));
    }
System.out.println(l);
//collect those into a Map
Map<String, Integer> result = l.stream().collect(Collectors.toMap(q -> q, q -> q.length()));

System.out.println(result);

      



your map might look like this:

{country = 7, name = 4, sport = 5, years = 5}

+1


source


You can use regex like

(.). *\1

to search for words that start and end with the same character.

+1


source


You can use streams.

public void test() {
    String s = "Hey my name is $name$; I have $years$ years old, and I love play $sport$ and I live in $country$ !";
    // Helps me maintain state of whether we are in a word or not.
    // Use AtomicBoolean as a `final` mutable value.
    final AtomicBoolean inWord = new AtomicBoolean(false);
    // Split on the `$` character and stream it.
    Map<String, Integer> myMap = Arrays.stream(s.split("\\$"))
            // Filter out the non-words (i.e. every other one).
            .filter(w -> inWord.getAndSet(!inWord.get()))
            // Generate the map.
            .collect(Collectors.toMap(w -> w, w -> String::length));
    System.out.println(myMap);
}

      

Printing

{country = 7, name = 4, sport = 5, years = 5}

0


source







All Articles