繁体   English   中英

Java 8 列表<V>进入地图<K, V>

[英]Java 8 List<V> into Map<K, V>

我想使用 Java 8 的流和 lambda 将对象列表转换为 Map。

这就是我在 Java 7 及更低版本中编写它的方式。

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

我可以使用 Java 8 和 Guava 轻松完成此操作,但我想知道如何在没有 Guava 的情况下执行此操作。

在番石榴中:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

以及带有 Java 8 lambdas 的 Guava。

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

根据Collectors文档,它很简单:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));

如果不能保证您的键对于列表中的所有元素都是唯一的,您应该将其转换为Map<String, List<Choice>>而不是Map<String, Choice>

Map<String, List<Choice>> result =
 choices.stream().collect(Collectors.groupingBy(Choice::getName));

使用getName()作为键, Choice本身作为映射的值:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));

这是另一个,以防您不想使用 Collectors.toMap()

Map<String, Choice> result =
   choices.stream().collect(HashMap<String, Choice>::new, 
                           (m, c) -> m.put(c.getName(), c),
                           (m, u) -> {});

列出的大多数答案都遗漏了列表具有重复项的情况 在这种情况下,答案将抛出IllegalStateException 请参阅以下代码来处理列表重复项

public Map<String, Choice> convertListToMap(List<Choice> choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName, choice -> choice,
            (oldValue, newValue) -> newValue));
  }

一种简单的方法

Map<String,Choice> map = new HashMap<>();
choices.forEach(e->map.put(e.getName(),e));

例如,如果要将对象字段转换为映射:

示例对象:

class Item{
        private String code;
        private String name;

        public Item(String code, String name) {
            this.code = code;
            this.name = name;
        }

        //getters and setters
    }

并操作将列表转换为地图:

List<Item> list = new ArrayList<>();
list.add(new Item("code1", "name1"));
list.add(new Item("code2", "name2"));

Map<String,String> map = list.stream()
     .collect(Collectors.toMap(Item::getCode, Item::getName));

如果您不介意使用 3rd 方库,AOL 的cyclops-react lib(披露我是贡献者)具有所有JDK 集合类型的扩展,包括ListMap

ListX<Choices> choices;
Map<String, Choice> map = choices.toMap(c-> c.getName(),c->c);

您可以使用 IntStream 创建索引的 Stream ,然后将它们转换为 Map :

Map<Integer,Item> map = 
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));

我试图这样做并发现,使用上面的答案,当使用Functions.identity()作为 Map 的键时,由于输入问题,我在使用像this::localMethodName的本地方法this::localMethodName来实际工作时this::localMethodName了问题.

Functions.identity()实际上做的东西打字在这种情况下,这样的方法只会通过返回的工作Object和接受的PARAM Object

为了解决这个问题,我最终放弃了Functions.identity()并使用s->s代替。

所以我的代码,在我的例子中列出目录中的所有目录,并且对于每个目录使用目录名称作为映射的键,然后使用目录名称调用方法并返回项目集合,如下所示:

Map<String, Collection<ItemType>> items = Arrays.stream(itemFilesDir.listFiles(File::isDirectory))
.map(File::getName)
.collect(Collectors.toMap(s->s, this::retrieveBrandItems));

我将编写如何使用泛型控制反转将列表转换为映射。 只是通用方法!

也许我们有整数列表或对象列表 所以问题如下:地图的关键应该是什么

创建界面

public interface KeyFinder<K, E> {
    K getKey(E e);
}

现在使用控制反转:

  static <K, E> Map<K, E> listToMap(List<E> list, KeyFinder<K, E> finder) {
        return  list.stream().collect(Collectors.toMap(e -> finder.getKey(e) , e -> e));
    }

例如,如果我们有 book 对象,这个类就是为地图选择 key

public class BookKeyFinder implements KeyFinder<Long, Book> {
    @Override
    public Long getKey(Book e) {
        return e.getPrice()
    }
}

我使用这种语法

Map<Integer, List<Choice>> choiceMap = 
choices.stream().collect(Collectors.groupingBy(choice -> choice.getName()));
Map<String, Set<String>> collect = Arrays.asList(Locale.getAvailableLocales()).stream().collect(Collectors
                .toMap(l -> l.getDisplayCountry(), l -> Collections.singleton(l.getDisplayLanguage())));

这可以通过两种方式完成。 让 person 成为我们将用来演示它的类。

public class Person {

    private String name;
    private int age;

    public String getAge() {
        return age;
    }
}

people成为要转换为地图的 Person 列表

1.在列表上使用简单的foreach和Lambda表达式

Map<Integer,List<Person>> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));

2.在给定列表上定义的流上使用收集器。

 Map<Integer,List<Person>> mapPersons = 
           persons.stream().collect(Collectors.groupingBy(Person::getAge));

可以使用流来做到这一点。 为了消除显式使用Collectors的需要,可以静态导入toMap (如 Effective Java 第三版所推荐)。

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

private static Map<String, Choice> nameMap(List<Choice> choices) {
    return choices.stream().collect(toMap(Choice::getName, it -> it));
}

这是StreamEx 的解决方案

StreamEx.of(choices).toMap(Choice::getName, c -> c);
Map<String,Choice> map=list.stream().collect(Collectors.toMap(Choice::getName, s->s));

甚至为我服务,

Map<String,Choice> map=  list1.stream().collect(()-> new HashMap<String,Choice>(), 
            (r,s) -> r.put(s.getString(),s),(r,s) -> r.putAll(s));

如果必须覆盖相同键名的每个新值:

public Map < String, Choice > convertListToMap(List < Choice > choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName,
            Function.identity(),
            (oldValue, newValue) - > newValue));
}

如果所有选项都必须分组在一个名称列表中:

public Map < String, Choice > convertListToMap(List < Choice > choices) {
    return choices.stream().collect(Collectors.groupingBy(Choice::getName));
}
List<V> choices; // your list
Map<K,V> result = choices.stream().collect(Collectors.toMap(choice::getKey(),choice));
//assuming class "V" has a method to get the key, this method must handle case of duplicates too and provide a unique key.

另一种可能性只存在于评论中:

Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(c -> c.getName(), c -> c)));

如果要将子对象的参数用作 Key,则很有用:

Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(c -> c.getUser().getName(), c -> c)));

作为guava的替代品,可以使用kotlin-stdlib

private Map<String, Choice> nameMap(List<Choice> choices) {
    return CollectionsKt.associateBy(choices, Choice::getName);
}
String array[] = {"ASDFASDFASDF","AA", "BBB", "CCCC", "DD", "EEDDDAD"};
    List<String> list = Arrays.asList(array);
    Map<Integer, String> map = list.stream()
            .collect(Collectors.toMap(s -> s.length(), s -> s, (x, y) -> {
                System.out.println("Dublicate key" + x);
                return x;
            },()-> new TreeMap<>((s1,s2)->s2.compareTo(s1))));
    System.out.println(map);

双键 AA

{12=ASDFASDFASDF, 7=EEDDDAD, 4=CCCC, 3=BBB, 2=AA}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM