亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

分組字符串 - Java

分組字符串 - Java

收到一只叮咚 2021-10-28 09:29:31
我有一個 ArrayList。我想對相似的項目進行分組,這樣 letter.pdf 是每個組中的第一個。例如:123_Letter.pdf123_Others.pdf123_More.pdf222_Second.pdf222_Letter.pdf222_Third.pdf222_Fourth.pdf123_File.pdf輸出應該是:**123_Letter.pdf**123_Others.pdf123_More.pdf123_File.pdf**222_Letter.pdf**222_Second.pdf222_Third.pdf222_Fourth.pdf每組中其他元素的順序無關緊要。列表中有 3000 多個元素。如您所見,僅排序并沒有多大幫助。我試過這樣的事情,但它缺少最后一個元素 123_File.pdf。有沒有更好的方法來做到這一點?請幫忙。String root = list.get(0).substring(0,4);        ArrayList<String> al = new ArrayList<>();        for (int i = 0; i < list.size(); i++) {            while (list.get(i).substring(0, 4).equals(root)) {                if (list.get(i).endsWith("etter.pdf")) {                    al.add(0, list.get(i));                    i++;                } else {                    al.add(list.get(i));                    i++;                }            }            System.out.println(al);            al = new ArrayList<>();            root = list.get(i).substring(0, 4);        }
查看完整描述

3 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

聽起來您想根據兩個標準進行排序:

  • 每個列表項中的前三個字符,以及

  • 每個列表項的其余內容,例如 Letter.pdf 首先出現。

一個老派的合理解決方案是實現 custom java.util.Comparator,并將其用作排序的基礎:

public static List<String> sortOldSchool(List<String> list){


    Comparator<String> comparator = new Comparator<String>(){

        private static final String LETTER = "Letter.pdf";

        public int compare(String orange, String apple){

            String ostart = orange.substring(0,3);

            String astart = apple.substring(0,3);

            if (ostart.equals(astart)){

                if (orange.endsWith(LETTER)){

                    return (apple.endsWith(LETTER)) ? 0 : -1;

                }

                else return (apple.endsWith(LETTER)) ? 1 : orange.compareTo(apple);

            }

            else return ostart.compareTo(astart);

        }

    };

    Collections.sort(list, comparator);

    return list;

}

一種更現代的方法是利用從 Java 8 開始可用的新功能范式:


public static List<String> sortFunctional(List<String> list){


    Comparator<String> firstThree= Comparator.comparing(item -> item.substring(0,3));

    Comparator<String> letter = Comparator.comparing(item -> (!item.endsWith("Letter.pdf")));

    return list.stream()

            .sorted(firstThree.thenComparing(letter))

            .collect(Collectors.toList());

}    


查看完整回答
反對 回復 2021-10-28
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

根據您的描述 - 我建議將問題分解為兩個子問題:

  • 步驟 1:將值組織到它們的前綴組中

  • 第 2 步:對每個前綴組中的值進行排序,確保值“_Letter.pdf”排在第一位。

我提供了一個代碼示例來演示以下每個步驟:

import java.util.*;

import java.util.function.Function;

import java.util.stream.Collector;

import java.util.stream.Collectors;

import java.util.stream.Stream;


import static java.util.stream.Collectors.toList;


public class StackoverflowTest {


    List<String> values = Arrays.asList(

            "123_Letter.pdf",

            "123_Others.pdf",

            "123_More.pdf",

            "222_Second.pdf",

            "222_Letter.pdf",

            "222_Third.pdf",

            "222_Fourth.pdf",

            "123_File.pdf");


    List<String> expected = Arrays.asList(

            "123_Letter.pdf",

            "123_Others.pdf",

            "123_More.pdf",

            "123_File.pdf",

            "222_Letter.pdf",

            "222_Second.pdf",

            "222_Third.pdf",

            "222_Fourth.pdf"

    );


    @Test

    public void sort() {

        // Basic function to group the values by the prefix

        Collector<String, ?, Map<String, List<String>>> groupByPrefix = Collectors.groupingBy(c -> c.substring(0, 3));


        // Basic function to sort the groups with _Letter.pdf first

        Function<List<String>, Stream<? extends String>> sortPrefixGroups = v ->

                v.stream().sorted(Comparator.comparing(i -> !i.endsWith("_Letter.pdf")));


        // Step 1: Organise the values into their prefix groups

        Map<String, List<String>> groupedByPrefix = new TreeMap<>(values.stream().collect(groupByPrefix));



        // Step 2: Sort each of the prefix groups and recombine them back into a list to maintain their internal order

        List<String> collect = groupedByPrefix.entrySet().stream().map(Map.Entry::getValue).flatMap(sortPrefixGroups).collect(toList());


        Assert.assertEquals(expected, collect);

        //Print just for fun

        collect.forEach(System.out::println);

    }

}


查看完整回答
反對 回復 2021-10-28
?
繁星點點滴滴

TA貢獻1803條經驗 獲得超3個贊

如何使用HashMap:


HashMap<String, List<String>> hashMap = new HashMap<String, List<String>>();

現在,遍歷哈希圖并添加元素:


if (!hashMap.containsKey(listItem.substring(0,2)) {

    List<String> items = new ArrayList<String>();

    items.add(listItem);


    hashMap.put(listItem.substring(0,2), items);

} else {

    hashMap.get(listItem.substring(0,2)).add(items);

}


查看完整回答
反對 回復 2021-10-28
  • 3 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號