java统计单词个数,使用数组链表实现排序

//使用数组链表实现map排序

public class Demo1 {
    //节点数组长度
    private static int nodeLength = 1;

    public static void main(String[] args) {
        String data = "hello word if you have something wo  public void main, string args hello word hello word too data split his hash his split data too to word word word";
        Demo1 demo = new Demo1();
        Map<String, Integer> map = demo.map(data);
        demo.print(demo.toNode(map));
    }

    private void print(Node[] nodes){
        for(int i = nodes.length - 1; i >= 0; i--){
            if(null == nodes[i]) continue;
            Node node = nodes[i];
            do{
                System.out.println(node.value + ":" + (i + 1));
                node = node.next;
            }while (null != node);
        }
    }


    public Node[] toNode(Map<String,Integer> map){
        Node[] nodes = new Node[nodeLength];
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            if(null == nodes[entry.getValue() - 1]){
                nodes[entry.getValue() - 1] = new Node(entry.getKey());
            }else{
                Node node = nodes[entry.getValue() - 1];
                Node next = new Node(entry.getKey());
                next.next = node.next;
                node.next = next;
            }
        }
        return nodes;
    }
    public Map<String,Integer> map(String data){
        data = data.replaceAll(" +"," ").replaceAll("[,|.|?]"," ");
        String[] split = data.split("\\s");
        Map<String,Integer>  result = new HashMap<>();
        for(String word : split){
            if(word.trim().equals("")) continue;
            if(null == result.get(word)){
                result.put(word,1);
            }else{
                int num = result.get(word) + 1;
                if(nodeLength < num){
                    nodeLength = num;
                }
                result.put(word,num);
            }
        }
        return result;
    }
    static class Node{
        String value;
        Node next;
        public Node(String value){
            this.value = value;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值