How to split an array by word length in Java

3 Answers

0 votes
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class MyClass {
    public static void main(String args[]) {
 
        String[] arr = new String[] { "java", "c", "c#", "c++", "rust", "python", "php"};
        
        Map<Integer, List<String>> mp = Arrays.stream(arr)
                                        .collect(Collectors.groupingBy(String::length));

        for (int i = 1; i < 6 + 1; i++) {
            System.out.println(i + " letters: " + mp.get(i));
        }
    }
}
   
   
   
   
/*
run:
   
1 letters: [c]
2 letters: [c#]
3 letters: [c++, php]
4 letters: [java, rust]
5 letters: null
6 letters: [python]
   
*/

 



answered Mar 12, 2023 by avibootz
0 votes
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class MyClass {
    public static void main(String args[]) {
 
        String[] arr = new String[] { "java", "c", "c#", "c++", "rust", "python", "php"};
        
        Map<Integer, List<String>> mp = Arrays.stream(arr)
                                        .collect(Collectors.groupingBy(String::length));

        for (Map.Entry<Integer, List<String>> e : mp.entrySet()) {
            System.out.println(e);
        }
    }
}
   
   
   
   
/*
run:
   
1=[c]
2=[c#]
3=[c++, php]
4=[java, rust]
6=[python]

*/

 



answered Mar 12, 2023 by avibootz
0 votes
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class MyClass {
    public static void main(String args[]) {
 
        String[] arr = new String[] { "java", "c", "c#", "c++", "rust", "python", "php"};
        
        Map<Integer, List<String>> mp = Arrays.stream(arr)
                                        .collect(Collectors.groupingBy(String::length));

        for (Map.Entry<Integer, List<String>> e : mp.entrySet()) {
            for (String s : e.getValue()) {
                System.out.print(s + " ");
            }
            System.out.println();
        }
    }
}
   
   
   
   
/*
run:
   
c 
c# 
c++ php 
java rust 
python 
   
*/

 



answered Mar 12, 2023 by avibootz
...