为了账号安全,请及时绑定邮箱和手机立即绑定

字符串的Java Bucket Sort程序

字符串的Java Bucket Sort程序

临摹微笑 2021-05-15 19:12:01
我遇到的主要问题是弄清楚如何将特定的字符串传递给存储桶类,以将每个字符串分成各自的存储桶。这是一项任务,我被困住了。我不需要解决方案,只需一些帮助即可将我指出正确的方向。注意:我必须在存储桶类中使用存储桶arraylist和链表import java.util.*;import java.io.*;public class Bucket {    private char minInitial;    private char maxInitial;    private LinkedList<String> list;    public Bucket (char min, char max) {        minInitial = min;        maxInitial = max;        list = new LinkedList<String>();    }    public static void main (String args[]) {        /* There are usually 8 for the entire alphabet because letters like c and s have more words for them than others */        ArrayList<Bucket> buckets = new ArrayList<>(8);        buckets.add(new Bucket('a', 'b'));        buckets.add(new Bucket('c', 'c'));        buckets.add(new Bucket('d', 'f'));        buckets.add(new Bucket('g', 'k'));        buckets.add(new Bucket('l', 'o'));        buckets.add(new Bucket('p', 'r'));        buckets.add(new Bucket('s', 's'));        buckets.add(new Bucket('t', 'z'));        File inFile;        PrintWriter outFile;        try {            inFile = new File("input.txt");//input.txt file has the words sepepatated by comma "cat,dog,boy,bye"            String path = inFile.getAbsolutePath();            //outFile = new PrintWriter("output.txt");            System.out.println("File Name:  "+ inFile +  "File Path: " + path);            //System.out.println("File Name: " + outFile);            Scanner fileScan = new Scanner(inFile);            String inputFile="";            while (fileScan.hasNext()) {                inputFile = fileScan.next();                System.out.println(inputFile);            }            String arrayString[] = inputFile.split(",");            Arrays.sort(arrayString); //sorts the strings alphabetically            for (int i =0; i<arrayString.length; i++) {                System.out.println("List elem " + i + ": " +arrayString[i]);                //traverses every element            }、
查看完整描述

2 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

如果您使用的是Java 8,则可以执行以下操作,将单词添加到相应的存储桶中:


Arrays.stream(arrayString)

.forEach(word -> buckets.stream()

    .filter(bucket -> bucket.minInitial <= word.charAt(0) && word.charAt(0) <= bucket.maxInitial)

    .findFirst().ifPresent(bucket -> bucket.list.add(word)));


查看完整回答
反对 回复 2021-05-19
  • 2 回答
  • 0 关注
  • 154 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信