Split a alphabetically sorted list into sublists based on alphabets in java

前端 未结 4 1423
时光取名叫无心
时光取名叫无心 2021-01-19 06:20

I have a sorted list in java, i just want to split this list into sublists based on the first alphabet at each index of list. For example List contains

{
cal         


        
相关标签:
4条回答
  • 2021-01-19 06:23

    If you are open to using a third-party library, Eclipse Collections 7.x will work with Java 6. Using Eclipse Collections MutableList you can call groupBy as follows:

    MutableList<String> list = 
            Lists.mutable.with("calculator", "catch", "doll", "elephant");
    Multimap<Character, String> multimap = 
            list.groupBy(StringFunctions.firstLetter());
    System.out.println(multimap); 
    // Prints {d=[doll], e=[elephant], c=[calculator, catch]}
    

    If you need to use a java.util.List for the Strings, then you can use the ListAdapter class.

    List<String> list =
            Arrays.asList("calculator", "catch", "doll", "elephant");
    Multimap<Character, String> multimap =
            ListAdapter.adapt(list).groupBy(StringFunctions.firstLetter());
    

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
  • 2021-01-19 06:37

    Something like this could work.

    private List<List<String>> subListOnFirstLetter(List<String> list) {
        List<List<String>> result = new ArrayList<>();
        char first = list.get(0).charAt(0);
        List<String> subList = new ArrayList<>();
        for (String element : list) {
            char next = element.charAt(0);
            if (next != first) {
                result.add(subList);
                subList = new ArrayList<>();
            } else {
                subList.add(element);
            }
            first = next;
        }
        return result;
    }
    
    0 讨论(0)
  • 2021-01-19 06:47

    You could use Java 8 Streams. Unfortunately, this method doesn't take advantage from the list being sorted already. list has to be the list containing your elements.

    Map<Character, List<String>> collect =
            list.stream().collect(Collectors.groupingBy(elem -> elem.charAt(0)));
    
    0 讨论(0)
  • 2021-01-19 06:50

    The solution of @SilverNak is good with Java-8, you can use this also if you are not using Java-8 :

    public static void main(String[] args) {
        String list[] = {"calculator", "catch", "doll", "elephant"};
        Map<Character, List<String>> map = new HashMap<>();
    
        List<String> lst;
        for (String str : list) {
            //if the key exit then add str to your list else add a new element
            if (map.containsKey(str.charAt(0))) {
                map.get(str.charAt(0)).add(str);
            } else {
                lst = new ArrayList<>();
                lst.add(str);
                map.put(str.charAt(0), lst);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题